📚 开源资源分享——颜佐光的个人书架
✉️ 联系站长
书架 / Java / SpringBoot

Spring Boot & MyBatis

2020-03-05 11:00 · 约 2,797 字 · 浏览 2,650 次 · 更新 2020-05-16 21:40SpringBoot

前面文章介绍了如何快速体验SpringBoot,但是在实际项目中作用不大,因为缺少了很多必要的组件。本文介绍如何快速接入MyBatis&MySQL

本文在一个可以运行的SpringBoot项目上增加配置,如果有疑问,可以参考SpringBoot七分钟快速实践

Spring Boot入门系列

配置

  • 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(东八区)

参考

com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别 serverTimezone设定

← 返回《Java》目录书架 →