Springboot mybatis配置及踩过的坑

springboot是近两年比较火爆的框架,比springMVC轻量,易用。但是新的东西用起来可能会多少有些小坑和需要熟悉的地方,本文从实践出发概述一下使用mybatis的配置方法,以及在配置过程中可能遇到的一些坑。

注:1. 本文用到的springboot版本为2.x版本,相较于1.x版本还是有些不同的。本着向前看的原则,以2.x为例。

      2.本文使用的gradle作为编译工具

一、springboot与mybatis配置

1.配置mybatis以及mysql依赖

compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
compile('mysql:mysql-connector-java')
compile('com.alibaba:druid-spring-boot-starter:1.1.9')

2.配置application.yaml配置文件

i.datasource

datasource:
  name: datasource
  url: jdbc:mysql://{$mysqlhost}:{$port}/{$db}?characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull
  username: xxxx
  password: xxxxxx
  driverClassName: com.mysql.jdbc.Driver
  max-active: 2
  max-idle: 2
  min-idle: 2
  initial-size: 2
  validation-query: select 1
  test-on-borrow: true
  test-on-return: false
  test-while-idle: false
  time-between-eviction-runs-millis: 3000
  min-evictable-idle-time-millis: 3000
  max-wait: 3000
  jmx-enabled: true
data:
  jpa:
    repository:
      enabled: true

ii.mybatis

mybatis:
  mapperLocations: classpath:mapper/*.xml

3.配置mybatis mapper、entity以及对应的xml

这块是mybatis正常使用方式,不再赘述太多细节,重点说一下需要注意的地方。一定要注意对应关系。

i. 重点说一下xml的创建配置:

1)xml中要注意命名与mapper interface的命名一致

2)xml中namespace要指定正确

<mapper namespace="com.xxx.dao.xxxMapper">

这个mapper就是定义dao方法的interface的mapper名字

3)xml中resultMap以及type定义正确,这个type就是对应的entity所指的类型

4)xml中所定义的id名称与mapper dao中对应方法的名字要一致,resultMap、 parameterType、resultType等设置正确

ii. 再看下mapper dao的创建,重点注意对应关系即可

@Mapper
public interface xxxMapper {

    List<xxxDO> selectByxxxAndyyy(@Param("xxx") String xxx, @Param("yyy") String yyy);
}

4.配置入口application

@SpringBootApplication
@MapperScan("com.xxx.dao")
public class Application {

这里需要注意的地方有两个:

1.增加@MapperScan("mapper dao的位置")

2.注意去掉@SpringBootApplication/@EnableAutoConfiguration的DataSource exclude配置 (exclude = {DataSourceAutoConfiguration.class}),因为之前可能没使用DataSource,但是配置使用之后需要去掉这个exclude。

至此,配置就完成了。如果配置正确顺利的话,应该可以成功启动并且访问对应的dao中的方法了。


下面说几个笔者配置过程中遇到的几个小坑:

1)application.yaml中配置mybatismapper位置不对。

一定要注意 

mapperLocations: classpath:mapper/*.xml

这个位置是在


2)忘记去掉了@SpringBootApplication中的(exclude = {DataSourceAutoConfiguration.class})

3)mapper中的xml文件,一定要是xxx.xml这种格式的。这个地方是个神坑。我找了好久才发现这个问题。配置完成后每次访问都报错:“.m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.xxx.dao.xxxMapper.selectxxxx”

反复检查了好几遍,最后发现,这个mapper xml文件竟然没有以xml为结尾后缀。这个地方是idea创建xml文件时的坑。创建的时候选择文件类型,但是名字里面并没有以xml为后缀。这样是match不到的。重命名加上.xml后缀,重启,完美解决!


尾注:文中马赛克了项目相关信息,不影响配置理解,有问题可以留言或者私信。


猜你喜欢

转载自blog.csdn.net/michaelgo/article/details/80825917