mybatis的学习5______使用注解实现CURD

1.dao层的UserMapper的编写:

public interface UserMapper {

    @Select("select * from user")
    List<User> getAllUser();

    //
    @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User u);

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

    //
    @Update("update user set pwd=#{pwd},name=#{name} where id=#{id}")
    int update(User u);

    //
    @Select("select * from user where id=#{id}")
    public User select(int id);
}

2.mybatis核心文件的编写(映射器):

 <mappers>
       <mapper class="com.xbf.dao.UserMapper"></mapper>
    </mappers>

3.实现事务的自动提交:

 public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSqlSession() {
        //开启事物的自动提交
        return sqlSessionFactory.openSession(true);
    }

 

4.测试类的编写:

public class UserTest {


    @Test
    public void getAllUser(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getAllUser();
        System.out.println(users);
        sqlSession.close();
    }

    @Test
    public void addUser(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u=new User(5,"劳务","555");
        int i = mapper.addUser(u);
        System.out.println(i);
    }

    @Test
    public void delete(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        User u=new User(5,"劳务","555");
        int i = mapper.delete(5);
        System.out.println(i);
    }

    @Test
    public void update(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       User u=new User(5,"老五","666");
        int i = mapper.update(u);
        System.out.println(i);
    }

    @Test
    public void select(){

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User i = mapper.select(5);
        System.out.println(i);
    }
}

 

posted @ 2019-07-24 13:06  德鲁大叔817  阅读(175)  评论(0编辑  收藏  举报