SpringBoot(三)SpringBoot整合MyBatis
MyBatis 是一款优秀的持久层框架,Spring Boot官方虽然没有对MyBatis进行整合,但是MyBatis团队自行适配了对应的启动器,进一步简化了使用MyBatis进行数据的操作
因为Spring Boot框架开发的便利性,所以实现Spring Boot与数据访问层框架(例如MyBatis)的整合非常简单,主要是引入对应的依赖启动器,并进行数据库相关参数设置即可
创建与数据库表相对应的实体类
public class Comment {
private Integer id;
private String content;
private String author;
private Integer aId;
}
public class Article {
private Integer id;
private String title;
private String content;
}
编写配置文件
在application.properties配置文件中进行数据库连接配置
#MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123
注解方式整合Mybatis
需求:实现通过ID查询Comment信息
public interface CommentMapper {
@Select("select * from t_comment where id = #{id}")
Comment findById(Integer id);
}
@SpringBootApplication
@MapperScan("com.szx.bootmybatis.mapper") //指定扫描mapper的包
public class BootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(BootmybatisApplication.class, args);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
class BootmybatisApplicationTests {
@Autowired
private CommentMapper commentMapper;
@Test
void findCommentById() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
}
控制台中查询的Comment的aId属性值为null,没有映射成功。这是因为编写的实体类Comment中使用了驼峰命名方式将t_comment表中的a_id字段设计成了aId属性,所以无法正确映射查询结果。
为了解决上述由于驼峰命名方式造成的表字段值无法正确映射到类属性的情况,可以在Spring Boot全局配置文件application.properties中添加开启驼峰命名匹配映射配置,示例代码如下
#开启驼峰命名规则
mybatis.configuration.map-underscore-to-camel-case=true
配置文件的方式整合MyBatis
@Mapper
public interface ArticleMapper {
public Article selectArticle(Integer id);
}
#设置扫描mapper.xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
#给实体类设置别名
mybatis.type-aliases-package=com.szx.bootmybatis.pojo
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.szx.bootmybatis.mapper.ArticleMapper">
<select id="selectArticle" parameterType="int" resultType="com.szx.bootmybatis.pojo.Article">
select * from t_article where id = #{id}
</select>
</mapper>
@RunWith(SpringRunner.class)
@SpringBootTest
class BootmybatisApplicationTests {
@Autowired
private ArticleMapper articleMapper;
@Test
void findArticleById() {
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}
}