1.MyBatis-Spring-Boot-Starter
MyBatis-Spring-Boot-Starter依赖将会提供如下
- 自动检测现有的DataSource
- 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
- 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
- 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。
使用了该Starter之后,只需要定义一个DataSource即可(application.properties或application.yml中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
2.src\main\resources\application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/bootdo?useUnicode=true&characterEncoding=utf8
username: root
password: root
initialSize: 3
maxActive: 100
minIdle: 10
maxWait: 50000
profiles:
#dev(info) or prod(error)
active: prod
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
servlet:
multipart:
enabled: true
max-file-size: 50Mb
max-request-size: 300Mb
#配置MyBatis
mybatis:
type-aliases-package: com.xxx.spring.mysqles.domain
mapper-locations: classpath:mybatis/*Mapper.xml
3.Springboot配置原理来源Spring 配置
最常用的应该是 Mapper
动态代理开发,但是动态代理配置也有两种,一般使用第二种,本人也是使用第二种。如果第二种 首先有几点要确定。
- *Mapper.java 和 *Mapper.xml 命名是否一致
- 是否在一个包下,扫描能不能扫到 .xml或者将 *Mapper.xml 放在
resources
下。 - *Mapper.xml 的 namespace 配置是否准确,接口方法名是否准确。
<!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 配置Mapper接口 -->
<property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper" />
<!-- 配置sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- Mapper动态代理开发 开发方式2 扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.guozh.bitbooks.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
问题说明
启动springboot中出现org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题,可参考
- 将 *Mapper.xml 复制一份到 resources 下,记得修改 mybatis 配置文件的路径。
- 在 pom.xml 中配置资源代码
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>