当前位置: 移动技术网 > IT编程>开发语言>Java > spring Boot与Mybatis整合优化详解

spring Boot与Mybatis整合优化详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

springboot官方文档

关于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。

如:

<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中需要如下配置:

<bean id="sqlsession" class="org.mybatis.spring.sqlsessiontemplate"> 
 <constructor-arg index="0" ref="sqlsessionfactory" /> 
</bean> 

现在,mybatis-spring-boot支持自动创建并注册sqlsessiontemplate,所以不需要以上配置了。

sqlsession对象注入,如下:

@autowired 
private sqlsession sqlsession; 

::真不知道既然下面④都能注入mappers了,那还要sqlsession对象有什么用。。::

④自动扫描mappers,将其关联到sqlsessiontemplate,并将mappers注册到spring容器中,以便注入到我们的beans中。

默认情况下,mybatis-spring-boot将搜索被@mapper注释标注的mappers。

文档中描述可以用mybatis-spring提供的@mapperscan标注,但我不会用。

mybatis-spring文档中解释@mapperscan注释跟配置mapperscannerconfigurer是同样的效果:

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标注使用如下:

@mapper 
public interface usermapper { 
 userinfo queryuser(@param(value = "userid") int id); 
}

那么在mybatis-spring-boot中需要配置的是mapper.xml目录:

mybatis: 
 mapper-locations: classpath:mapper/*.xml 

总结

以上所述是小编给大家介绍的spring boot与mybatis整合优化详解,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网