mybatis使用注解的方式实现简单的crud

在对应的Mapper接口中编写:

//查询所有
@Select("select * from mybatis.user")
List<User> getUsers();

//通过性别查询
@Select("select * from mybatis.user where sex=#{sex}")
List
<User> getUserBySex(@Param("sex")String sex); //添加 @Insert("insert into mybatis.user values(#{username},#{pswd},#{sex})") int addUser1(User user); //通过username删除 @Delete("delete from mybatis.user where username = #{username}") int delByUsername1(@Param("username")String username); //通过username修改 @Update("update mybatis.user set sex=#{sex} where username = #{username}") int update1(User user);

编写测试java代码进行测试:

@Test
public void selAlls(){ //查询所有
   SqlSession sqlSession = MybatisUtils.getSqlSession();
   UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
   List<User> users = userMapper.getUsers();
   for(User user:users){
       System.out.println(user);
   }
   sqlSession.close();
 }
@Test
//查询通过Sex public void getUserBySex(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.getUserBySex("男"); for(User user:users){ System.out.println(user); } sqlSession.close(); } @Test public void addUser1(){ //添加 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.addUser1(new User("hahaha","psw123","女")); sqlSession.commit(); sqlSession.close(); }
@Test
public void delByUsername1(){ //通过username删除 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.delByUsername1("hahaha"); sqlSession.commit(); sqlSession.close(); } @Test public void update1(){ //修改 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.update1(new User("小张","aabb1122","男")); sqlSession.commit(); sqlSession.close(); }

@Param(),只要是传递基本数据类型,建议都加上。

posted @ 2020-08-29 22:01  曾经沧海难为水。  阅读(186)  评论(0编辑  收藏  举报