spring-boot与mybatis整合优化介绍

转载自 http://www.voidcn.com/blog/gongsunjinqian/article/p-6222069.html


关于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 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,200评论 19 139
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,019评论 0 2
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,781评论 0 4
  • http://blog.csdn.net/app_ios/article/details/52596230 The...
    pockyzhang阅读 850评论 0 0