Mybatis注解学习-增删改查

自动提交事务:

Mybatis注解学习-增删改查

增删改查:去掉了Mapper.xml文件,改成了使用注解:

Mybatis注解学习-增删改查

Mybatis注解学习-增删改查

import com.ftz.Demo.dao.UserMapper;
import com.ftz.Demo.po.User;
import com.ftz.Demo.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class TestUser {


   @Test
    public  void  Test(){
       SqlSession sqlSession = MybatisUtil.getSqlSession();
       UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       mapper.addNewUser(new User(13,"helloo","123321"));
       sqlSession.close();
   }

   @Test
   public void  Find(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.getUserBuId(9);
      sqlSession.close();

   }
   @Test
   public void  IdTest(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.updateUser(new User(5,"范直至","123456"));
      sqlSession.close();

   }

   @Test
   public  void DeleteUser(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.Delete(8);
      sqlSession.close();

   }


}

配置文件:

Mybatis注解学习-增删改查

对比之前:

Mybatis注解学习-增删改查

测试代码几乎一样:

import com.ftz.Demo.dao.UserMapper;
import com.ftz.Demo.po.User;
import com.ftz.Demo.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class TestUser {


   @Test
    public  void  Test(){
       SqlSession sqlSession = MybatisUtil.getSqlSession();
       UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       mapper.addNewUser(new User(13,"helloo","123321"));
       sqlSession.close();
   }

   @Test
   public void  Find(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.getUserBuId(9);
      sqlSession.close();

   }
   @Test
   public void  IdTest(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.updateUser(new User(5,"范直至","123456"));
      sqlSession.close();

   }

   @Test
   public  void DeleteUser(){
      SqlSession sqlSession = MybatisUtil.getSqlSession();
      UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      mapper.Delete(8);
      sqlSession.close();

   }


}

这里说两个小细节,那就是在注释中的sql语句:举个例子:

1:

@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")

这里的除了user(id,name,pwd) 这个地方的括号里面的名字需要对应数据库中的名字,其他的都是要和实体类对应的,自己的的实体类构造方法名字相对应!

2:在括号中使用参数的时候:举个例子:


    @Delete("delete from user where id = #{uid}")
    int Delete(@Param("uid") int id);

这里的注解里面是uid,那么#{}这个括号里面的必须对应这个注解里面设置的名字,就不是实体类中的名字了

上一篇:mybatis-测试二级缓存


下一篇:在MyBatis中使用注解实现增删改查