Mybatis入门之CRUD

xml元素

  • namespace
    xml中的namespace与dao接口的包名一致
  • id
    xml中的id与dao接口的方法名一致
  • resultType
    sql语句执行的返回值
  • parameterType
    参数类型
select
  1. 编写接口
//查询全部用户 List getUserList();

  1. 编写sql语句
select * from mybatis.user

  1. 测试
@Test public void test(){ //获得SqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //方式一:执行SQL推荐 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List userList = userMapper.getUserList(); //方式二: //List userList = sqlSession.selectList("com.sunfl.dao.UserDao.getUserList"); for (User user : userList) { System.out.println(user); }//关闭sqlSession sqlSession.close(); }

insert
  1. 编写接口
//新增一个用户 int addUser(User user);

  1. 编写sql语句
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});

  1. 测试
@Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.addUser(new User(4, "哈哈哈", "12323")); sqlSession.commit(); sqlSession.close(); }

update
  1. 编写接口
//更新一个用户 int updateUser(User user);

  1. 编写sql语句
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};

  1. 测试
@Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User(4,"嘿嘿","1111")); sqlSession.commit(); sqlSession.close(); }

delete
  1. 编写接口
//删除一个用户 int deleteUser(int id);

  1. 编写sql语句
delete from mybatis.user where id = #{id};

  1. 测试
@Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(4); sqlSession.commit(); sqlSession.close(); }

    推荐阅读