【MyBatis笔记】使用注解开发

【MyBatis笔记】使用注解开发,第1张

在方法前使用注解的方式

绑定接口到核心配置文件中:

本质:使用反射

底层:动态代理

使用注解进行增删改查:

自动提交事务: 

工具类:

public interface UserMapper {

    @Select("select * from user")
    //获取全部用户
    ListgetUser();


//    ---------------------------------------------
    //方法存在多个参数,所有的参数前面必须加上@Param("")
    @Select("select * from user where id=#{id}")
    //获取id获取用户
    User getUserById(@Param("id") int id);
//  ------------------------------------------------

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

// ---------------------------------------------------

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

    @Delete("delete from user where id=#{id}")
    int deleteUser(@Param("id")int id);
}
public class User {
    private int id;
    private String name;
    private String pwd;
    getter setter tostring;
}

 测试类

    @Test
    public void getUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List user = mapper.getUser();
        for (User user1 : user) {
            System.out.println(user1);
        }
        sqlSession.close();
    }
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(2);
        System.out.println(userById);
        sqlSession.close();
    }
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(6,"哈哈哈是的","76543"));
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap map = new HashMap<>();
        map.put("id",2);
        map.put("name","2two");
        map.put("pwd","lasf");
        mapper.updateUser(map);
        sqlSession.close();
    }
    @Test
    public void delete(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(2);
        sqlSession.close();
    }

Mybatis详细执行流程:
  1. Resource获取全局配置文件

  2. 实例化SqlsessionFactoryBuilder

  3. 解析配置文件流XMLCondigBuilder

  4. Configration所有的配置信息

  5. SqlSessionFactory实例化

  6. trasactional事务管理

  7. 创建executor执行器

  8. 创建SqlSession

  9. 实现CRUD

  10. 查看是否执行成功

  11. 提交事务

  12. 关闭

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/731437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存