MyBatisCRUD

首页 > MyBatisCRUD > 列表

MyBatisCRUD

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相关文章