xml元素
- namespace
xml中的namespace与dao接口的包名一致 - id
xml中的id与dao接口的方法名一致 - resultType
sql语句执行的返回值 - parameterType
参数类型
- 编写接口
//查询全部用户
List getUserList();
- 编写sql语句
select * from mybatis.user
- 测试
@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
- 编写接口
//新增一个用户
int addUser(User user);
- 编写sql语句
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
- 测试
@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
- 编写接口
//更新一个用户
int updateUser(User user);
- 编写sql语句
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
- 测试
@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
- 编写接口
//删除一个用户
int deleteUser(int id);
- 编写sql语句
delete from mybatis.user where id = #{id};
- 测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
推荐阅读
- 框架|Mybatis的一级缓存和二级缓存
- Mybatis日志工厂
- MyBatis的功能架构是怎样的
- mybatis之缓存机制
- Mybatis练习(1)
- Java|MyBatis(五)——MyBatis中的缓存机制
- mybatis之脚本解析器
- mybatis|记mybatis查询null字段导致的NPE
- Mybatis 动态查询、插入、修改操作