SpringBoot官方文檔http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
關于spring-boot與mybatis整合優化方面的介紹,就是Mybatis-Spring-boot-starter的介紹:
1、取消spring-mybatis.xml配置
①自動檢測已存在的Datasource
之前,需要在spring-mybatis.xml中配置datasource的Bean,現在只需要在application.yml中配置到spring.datasource節點下就可以。因為mybatis-spring-boot支持自動檢測已存在的Datasource。
②將創建并注冊SqlSessionFactoryBean實例,并傳入Datasource。
在mybatis中,sqlsession可以有SqlSessionFactory創建;而在mybatis-spring中則需要SqlSessionFactoryBean來創建,并傳入datasource。
如:
1
2
3
4
5
6
|
<bean id= "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > <property name= "configLocation" > <value>classpath:mybatis/mapper.xml</value> </property> <property name= "dataSource" ref= "dataSource" /> </bean> |
現在,mybatis-spring-boot支持自動創建并注冊SqlSessionFactoryBean,所以以上的配置都不需要了。
③將從SqlSessionFactoryBean中創建并注冊SqlSessionTemplate
SqlSessionTemplate是SqlSession的實現類,較SqlSession的默認實現類DefaultSqlSession來說,是線程安全的。
在mybatis-spring中需要如下配置:
1
2
3
|
<bean id= "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > <constructor-arg index= "0" ref= "sqlSessionFactory" /> </bean> |
現在,mybatis-spring-boot支持自動創建并注冊SqlSessionTemplate,所以不需要以上配置了。
SqlSession對象注入,如下:
1
2
|
@Autowired private SqlSession sqlSession; |
::真不知道既然下面④都能注入mappers了,那還要SqlSession對象有什么用。。::
④自動掃描mappers,將其關聯到SqlSessionTemplate,并將mappers注冊到spring容器中,以便注入到我們的beans中。
默認情況下,mybatis-spring-boot將搜索被@Mapper注釋標注的mappers。
文檔中描述可以用mybatis-spring提供的@MapperScan標注,但我不會用。
Mybatis-Spring文檔中解釋@MapperScan注釋跟配置MapperScannerConfigurer是同樣的效果:
1
2
3
4
5
|
public @interface MapperScan Use this annotation to register MyBatis mapper interfaces when using Java Config. It performs when same work as MapperScannerConfigurer via MapperScannerRegistrar. <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basePackage" value= "com.example.mappers" /> <property name= "sqlSessionFactoryBeanName" value= "sqlSessionFactory" ></property> </bean> |
現在,mybatis-spring-boot支持使用@Mapper注釋標注mappers接口類了,所以就不需要上述配置。
::其實感覺上述配置還是挺好的,不用每個mapper接口都注釋@Mapper。。。::
@Mapper標注使用如下:
1
2
3
4
|
@Mapper public interface UserMapper { UserInfo queryUser( @Param (value = "userId" ) int id); } |
那么在mybatis-spring-boot中需要配置的是mapper.xml目錄:
1
2
|
mybatis: mapper-locations: classpath:mapper/*.xml |
總結
以上所述是小編給大家介紹的spring Boot與Mybatis整合優化詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/gongsunjinqian/article/details/52710557