本文记录学习在SpringBoot中使用Mybatis。
一 什么是Mybatis
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录(官方定义);
官方使用示例代码如下:
String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101);} finally { session.close();}
通过示例程序可以看到它的执行过程主要有以下几个步骤:
1 应用程序启动时,根据配置文件生成一个SqlSessionFactory;
2 通过SqlSessionFactory的到一个SqlSession;
3 SqlSession内部通过Excutor执行对应的SQl;
4 返回处理结果;
5 释放资源;
二 SpringBoot集成Mybatis
Mybatis使用有2中方式,一种是使用注解,即在接口定义的方法上通过注解写入要执行的SQL和要完成的数据映射;一种是使用xml配置文件即在xml文件中写相关SQL和完成表与实体的映射。本文我们使用xml文件。
首先需要引入SpringBoot集成Mybatis的依赖jar包,这里我们只引入了Spring与Mybatis集成的包,springboot默认会自动帮我们引入其他依赖的jar包。
org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2
在application.properties文件中配置数据库连接信息和指定mybatis的接口对应的xml
#datasourespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456#mybatismybatis.mapper-locations=classpath:mybatis/*.xml
如上,我们的mapper xml文件放在reources目录下的mybatis文件夹下
写一个接口,定义我们要完成的功能
@Mapperpublic interface UserMapper { /** * 根据ID删除 */ int deleteByPrimaryKey(Long id); /** * 新增 */ int insert(UserInfo record); /** * 根据ID查询 */ UserInfo selectByPrimaryKey(Long id); /** * 修改 */ int updateByPrimaryKey(UserInfo record); /** * 查询所有 */ ListselectAll();}
@Mapper 该注解说名当前类是一个Mybatis的Mapper接口类,交给spring管理,令一种方式是使用注解 @MapperScan(basePackages="...") 说明basePackages及其子包下的接口都交给spring管理,我们多数情况下都会使用@MapperScan这个注解,这样我们就不用在每一个Mapper接口上写注解了。
在xml文件中完成SQl,实现具体的方法,如下:id, age, name delete from t_user where id = #{id,jdbcType=BIGINT} insert into t_user (id, age, name) values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) update t_user set age = #{age,jdbcType=INTEGER}, name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=BIGINT}
从这个xml文件,我们可以看到以下几点:
1 namespace="org.allen.demo.dao.UserMapper" 通过namespace来指定将当前xml文件的SQL实现的对应的接口Mapper
2 通过 resultMap 完成实体类与数据库表字段的映射
3 xml中的SQL语句都必须写在<select> <insert> <update><delete>内部
4 每一个标识的id都必须与接口中的方法名保持一直
5 insert 中使用的 useGeneratedKeys 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。如果设置了true,我们就可以在insert完成后直接通过当前操作的实体类获取数据库主键。
三 测试
使用Junit做测试
@RunWith(SpringRunner.class)@SpringBootTestpublic class MybatisApplicationTests { @Resource private UserMapper userMapper; @Test public void save() { UserInfo user = new UserInfo(); user.setName("world"); user.setAge(2); userMapper.insert(user); System.out.println("保存后的ID:" + user.getId()); } @Test public void delete() { long id = 5; userMapper.deleteByPrimaryKey(id); } @Test public void update() { UserInfo user = new UserInfo(); user.setName("world"); user.setAge(5); long id = 3; user.setId(id); userMapper.updateByPrimaryKey(user); } @Test public void selectById() { long id = 3; userMapper.selectByPrimaryKey(id); } @Test public void selectAll() { ListuserList = userMapper.selectAll(); } }