SpringDataJdbc整合MyBatis方式

由于官方文档springdatajdbc整合mybatis过于简述,导致死磕了一段时间,

  SpringDataJdbc整合Mybatis的官方文档:https://docs.spring.io/spring-data/jdbc/docs/2.0.0.RELEASE/reference/html/#jdbc.mybatis

至于选择SpringDataJdbc + Mybatis这个原因,就是可以手动控制SQL语句并且基本的单表SQL直接可以继承 CrudRepository 接口,不用再写那些基本的SQL了,复杂的查询直接可以定义在Mapper的XML文件里

此Demo项目的Git地址:https://github.com/starSmallDream/MySpringJDBCAndMyBatisExample.git

本人spring boot Maven项目,在pom文件加入mybatis和springdatajdbc的依赖

<dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.4</version>
</dependency>

<dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.4</version>
</dependency>
<dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

然后按照官方文档进行配置Bean,当然,这些SqlSessionFactoryBeansqlSessionTemplate已经由mybatis-spring-boot-starter依赖自动配置完了,所以,可以省略下面的Bean配置

@Configuration
@EnableJdbcRepositories
@Import(MyBatisJdbcConfiguration.class)
class Application {

  @Bean
  SqlSessionFactoryBean sqlSessionFactoryBean() {
    // Configure MyBatis here
  }
}

如果到这里还是启动找不到Mapper接口的方法的话,那就是需要配置下NamespaceStrategy接口实现,根据自己的包结构进行返回Mapper接口的位置,由于这是通过 实体类(包名) + Mapper 命名的方式查找Mapper接口文件的,所以文件名还是需要规范下的。

这是我根据自己包的位置进行配置下Mapper文件的寻找路径:

第一步:实现 NamespaceStrategy 接口

 第二部:

MyBatisJdbcConfiguration 此类的方法copy出来,因为要使用我们自定义的命名空间策略

 看这个类里面的代码,你会找到为什么会执行不了Mapper文件的SQL语句

下图是此Configuration配置类的内容

 

因为 对应的Mapper文件存在要执行的方法名的SQL语句,则优先执行Mapper文件的,否则,会执行CrudRepository里面的代码,因为我的Mapper接口文件继承了CrudRepository接口。

 这样,可以使用Mybatis的XML文件又可以使用基于SpringDataJdbc依赖的注解和方法名语义执行SQL了。。。

 

 

 
复制请注明出处,在世界中挣扎的灰太狼
原文地址:https://www.cnblogs.com/XingXiaoMeng/p/12975405.html