对于简单的数据库操作可以使用注解开发,对于复杂的数据库操作不推荐使用!!
mybatis 的常用注解:
@Insert:新增
@Update:更新
@Delete:删除
@Select:查询
@Result:实现结果集封装
@ResultMap:实现引用
@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
注解开发的基本流程:
1.编写Mapper接口
2.在核心配置文件中注册Mapper接口
3.测试
注解的CRUD:
UserMapper
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
@Select("select * from mybatis.user where id=#{id}")
User getUserById(@Param("id") int id);
@Insert("insert into mybatis.user values (#{id},#{name},#{password})")
int addUser(User user);
@Delete("delete from user where id=#{id}")
int delUser(@Param("id") int id);
@Update("update user set name=#{name} where id=#{id}")
int updateUser(@Param("id") int id,@Param("name") String name);
}
mybatis-conifg.xml
<!--绑定接口-->
<mappers>
<mapper class="com.zuo.dao.UserMapper"/>
</mappers>
UserDaoTest.java
public class UserDaoTest {
@Test
public void getUserList(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUsers();
for(User user:userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"mmmm","12346"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void delUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(0);
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(4,"zuozuozuo");
sqlSession.close();
}
}
标签:mapper,UserMapper,public,sqlSession,开发,user,注解,id From: https://www.cnblogs.com/zuok/p/17029171.html