Mybatis使用注解开发

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

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

1.查询方法

mapper的编写

  /**
     * Gets user.
     *
     * @return the user
     */
    @Select("SELECT * FROM USER")
    List<User> getUser();

    /**
     * Add user map int.
     *
     * @param map the map
     * @return the int
     */
    @Insert("insert into ljqdb.user (username, password) VALUES (#{name},#{pass})")
    int addUserMap(Map<String,Object> map);

    /**
     * Delete user int.
     *
     * @param id the id
     * @return the int
     */
    @Delete(" delete from ljqdb.user where id = #{id}")
    int deleteUser(int id);

    /**
     * Up user int.
     *
     * @param user the user
     * @return the int
     */
    @Update("update ljqdb.user set username=#{username},password=#{password} where id = #{id}")
    int upUser(User user);

测试类的编写

public class UserTest {

    /**
     * Up user.
     */
    @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();
    }

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

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

    /**
     * Get user.
     */
    @Test
    public void getUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> user = mapper.getUser();
        for (User user1 : user) {
            System.out.println(user1);
        }
        sqlSession.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LeeGaKi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值