前面文章介绍了如何快速体验SpringBoot,但是在实际项目中作用不大,因为缺少了很多必要的组件。本文介绍如何快速接入MyBatis&MySQL
本文在一个可以运行的SpringBoot项目上增加配置,如果有疑问,可以参考SpringBoot七分钟快速实践
- Spring Boot七分钟快速实践
- Spring Boot & MyBatis
- Spring Boot & Redis
- Spring Boot & Swagger
- Spring Boot & 单元测试
- Spring Boot & Actuator
- Spring Boot Admin
配置
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/tenmao?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
spring.datasource.username=tenmao_user
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
驱动类使用
com.mysql.cj.jdbc.Driver
,而不是com.mysql.jdbc.Driver
。区别参考com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别 serverTimezone设定
- 其他常用配置
# 开启下划线转驼峰
mybatis.configuration.map-underscore-to-camel-case=true
# 设置mapper文件路径
mybatis.mapper-locations=classpath:mapper/*.Mapper.xml
# 设置TypeHandler包名
mybatis.type-handlers-package=com.tenmao.handler
- XxxMapper
在各个XxxMapper(也可以是XxxDao接口)接口上添加注解org.apache.ibatis.annotations.Mapper
@Mapper
public interface PersonMapper {
@Select("SELECT * FROM person WHERE id=#{id}")
Person getOne(@Param("id") int id);
}
注意事项
- 可以开启debug模式,方便分析错误原因:
application.properties
中添加一行debug=true
常见错误
-
No MyBatis mapper was found in '[com.tenmao]' package
: 需要在XxxMapper接口上添加注解org.apache.ibatis.annotations.Mapper
-
DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
:忘记配置spring.datasource.url
了 -
RuntimeException: Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class loader or Thread context classloader
:pom文件中需要添加依赖mysql-connector-java
-
InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
: 需要在配置项spring.datasource.url
配置中添加serverTimezone=GMT%2B8
(东八区)