Mybatis使用注解开发

Mybatis使用注解开发,第1张

Mybatis使用注解开发

首先mybatis配置文件中注册mapper.class,实质用反射机制实现

底层用的动态代理注解需要在接口上实现,脱离mapper.xml

1.查询方法

mapper的编写

  
    @Select("SELECT * FROM USER")
    List getUser();

    
    @Insert("insert into ljqdb.user (username, password) VALUES (#{name},#{pass})")
    int addUserMap(Map map);

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

    
    @Update("update ljqdb.user set username=#{username},password=#{password} where id = #{id}")
    int upUser(User user);

测试类的编写

public class UserTest {

    
    @Test
    public void upUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(3, "我爱你", "123");
        mapper.upUser(user);
        sqlSession.commit();
        sqlSession.close();
    }

    
    @Test
    public void delUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int id = 6;
        mapper.deleteUser(id);
        sqlSession.commit();
        sqlSession.close();
    }

    
    @Test
    public void add(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //创建map接收
        Map map = new HashMap<>();
        map.put("name", "麻子黄");
        map.put("pass", "xiao");
        mapper.addUserMap(map);
        //提交事务
        sqlSession.commit();
        //关闭sqlSession实例
        sqlSession.close();
    }

    
    @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();
    }
}

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

原文地址: http://outofmemory.cn/zaji/5694996.html

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

发表评论

登录后才能评论

评论列表(0条)

保存