RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
springBoot与Mybatis整合优化详解

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。

如:

 
  
  classpath:mybatis/mapper.xml 
  
  
 

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

③将从SqlSessionFactoryBean中创建并注册SqlSessionTemplate

SqlSessionTemplate是SqlSession的实现类,较SqlSession的默认实现类DefaultSqlSession来说,是线程安全的。

在mybatis-spring中需要如下配置:

 
  
 

现在,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.
 
  
  
 

现在,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整合优化详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!


分享文章:springBoot与Mybatis整合优化详解
当前链接:http://sczitong.cn/article/pdojjh.html