Spring Boot & MyBatis

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

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

配置

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

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 平时用eclipse比较多,自学springboot的时候转用idea,所以有些操作不是很熟悉,在这里记录一下遇到...
    取名废同学阅读 1,581评论 0 0
  • 本文旨在用最通俗的语言讲述最枯燥的基本知识 最近身边的程序员掀起了学习springboot的热潮,说什么学会了sp...
    Java黎先生阅读 1,494评论 0 13
  •   最近在准备做毕设,由于需要后台,所以得学习一下后台的相关知识。之前学过JavaWeb的servlet的那套,不...
    琼珶和予阅读 2,922评论 1 5
  • 今天和两年前的今天一样,还是那么的冷,从早上开始风旋着旋着从脚底一直吹到头顶,吹得心都凉了,而我也和两年前一样起的...
    LiangLY158阅读 153评论 0 0
  • 儿子说,妈妈才是不容易寂寞的人,因为妈妈喜欢看书歌唱,喜欢网购旅游,喜欢思考奔跑,喜欢买菜做饭……还有很多...
    龙青阅读 267评论 0 2