码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatisCRUD

时间:2021-03-01 13:18:43      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:返回   pojo   str   参数   use   ssi   from   void   sele   

namespace

namespace中的包名要和DAO/mapper接口中的包名一致

Select

选择,查询语句

  • id:就是对应的namespace中的方法名
  • resultType: Sql语句执行的返回值 -> Class
  • parameterType: 参数类型
  1. 编写接口
    //根据ID查询用户
    User getUserById(int id);
  1. 编写Mapper对应的sql语句
    <select id="getUserById" resultType="com.ultraBlast.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id};
    </select>

3.测试

    @Test
    public void getUserById() {

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUserById(1);
            System.out.println(user.toString());
        }
    }

Insert

    @Test
    public void insertUser() {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            int res = userMapper.addUser(new User(5, "UB", "123456"));
            if (res > 0) {
                System.out.println("添加成功!");
            }
            sqlSession.commit();
        }
    }

Update

    @Test
    public void updateUser() {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            int res = userMapper.updateUser(new User(2, "赵六", "123456"));
            sqlSession.commit();
        }
    }

delete

    @Test
    public void deleteUser() {
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            int res = userMapper.deleteUser(1);
            sqlSession.commit();
        }
    }
**注意点**
+ 增删改需要提交事务

MyBatisCRUD

标签:返回   pojo   str   参数   use   ssi   from   void   sele   

原文地址:https://www.cnblogs.com/UltraBlast/p/14457286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!