zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    普通索引和唯一索引的选择
    深入理解MySQL索引(上)
    深入理解MySQL索引(下)
    Python3爬取小说并保存到文件
    MySQL45讲:一条update语句是怎样执行的
    IO软件层次结构与假脱机技术
    一条查询SQl是怎样执行的
    MySQL45讲笔记-事务隔离级别,为什么你改了数据我看不见
    了解一下IO控制器与控制方式
    3.6类别不平衡问题
  • 原文地址:https://www.cnblogs.com/xbfchder/p/11237336.html
Copyright © 2011-2022 走看看