SpringBoot整合MyBatis

转载请在文章最上方加上此句话:原文地址:http://www.cnblogs.com/zhuxiaojie/p/5836159.html

 

 

 

前言:这段时间用 springboot 感觉确实挺好用的,很大程度上的简化了开发,由其是它的自动化配置,让大大的提高了开发效率,现在我们要让 SpringBoot 与 MyBatis 一起工作。

 

 

注:1. 本人亲测可用,包括事务。

  2. 使用注解形式,全程无 MyBatis 与 Spring 的配置文件

  3. 文章时间为 2016-9-3 日,使用的是 MyBatis 官方提供的 mybatis-spring-boot-starter,当前最新版本为 1.1.1。

  4.mybatis-spring-boot-starter 的 github 源码地址为:https://github.com/mybatis/spring-boot-starter

  5.mybatis-spring-boot-stater 的官方文档地址为:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 

方法一:多数据源的 mytis

强烈推荐: 只要一行注解,使用 mybatis 的多数据源,无需要任何配置

 

github 地址:https://gitee.com/xiaojiezhu/mybadis-starter.git

使用方法如下,先加入如下配置文件,在 yaml 中

mysql:
  server:
    saas:
      url: "jdbc:mysql://localhost:3306/saas?useUnicode=true&characterEncoding=utf8"
      username: root
      password: 123
      driverClassName: com.mysql.jdbc.Driver
      initialSize: 1  #初始化大小
      minIdle: 1  #空闲连接池的大小
      maxActive: 50 #最大激活数量
    saas2:
      url: "jdbc:mysql://localhost:3306/saas2?useUnicode=true&characterEncoding=utf8"
      username: root
      password: 123
      driverClassName: com.mysql.jdbc.Driver
      initialSize: 1  #初始化大小
      minIdle: 1  #空闲连接池的大小
      maxActive: 50 #最大激活数量

如上是定义了两个数据源

然后在 main 方法所在类加上此注解

 

@MyBadisLoader({"saas = com.llc.admin.web.dao.saas = classpath:mapper/*xml" , 
                "saas2 = com.llc.admin.web.dao.saas2 = classpath:mapper/*.xml,classpath:mapper/user/*.xml"})
@SpringBootApplication
public class WebApplication {
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
    SpringApplication.run(WebApplication.</span><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">,args);
}

}

 

上面的注解中 saas 是上方配置文件,数据源的名称,后面是扫描的接口包名,可以用逗号分隔传入多个,再后面是扫描 xml 的配置文件路径,也支持多个 注解中接收的是一个数组,所以支持多个数据源,除此不需要任何代码就可以使用

 

就可以直接支持多数据源

 

下面方法二是使用 mybatis 官方的 starter,需要经过一些配置才行

 

 

 

 

 

 

 

 

方法二:使用 mybatis 官方 starter

首先加入 mybatis-spring-boot-stater 的 Maven 依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

 

 

配置数据源,这里使用的 dbcp 的数据源,具体大家可以看自己的情况来使用

在 src/main/resource 中,添加一个 prop.properties 配置文件,这里面添加了一些数据库连接的信息

#jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.137.2:3306/weichat?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=2335
jdbc.maxIdel=120
jdbc.maxWait=100

 

然后加上下面的代码注入数据源

@Configuration
// 这个注解导入刚才增加的 jdbc 配置文件 @PropertySource(
"classpath:prop.properties") public class DataSourceConfiguration { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${jdbc.maxActive}") private int maxActive; @Value("${jdbc.maxIdel}") private int maxIdel; @Value("${jdbc.maxWait}") private long maxWait;
@Bean
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> BasicDataSource dataSource(){
    BasicDataSource dataSource </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> BasicDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxIdle(maxIdel);
    dataSource.setMaxWait(maxWait);
    dataSource.setValidationQuery(</span>"SELECT 1"<span style="color: rgba(0, 0, 0, 1)">);
    dataSource.setTestOnBorrow(</span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> dataSource;
}

}

 

 

 

增加 MyBatis 的配置

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/**

  • @author zxj

*/
@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource;

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> PlatformTransactionManager annotationDrivenTransactionManager() {
     </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> DataSourceTransactionManager(dataSource);
}

@Bean(name </span>= "sqlSessionFactory"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactory sqlSessionFactoryBean() {
    SqlSessionFactoryBean bean </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactoryBean();
    bean.setDataSource(dataSource);

    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> bean.getObject();
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
        e.printStackTrace();
        </span><span style="color: rgba(0, 0, 255, 1)">throw</span> <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> RuntimeException(e);
    }
}

@Bean
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionTemplate(sqlSessionFactory);
}

}

 

 

然后需要配置 MyBatis 配置文件的路径,这个配置需要与上面的配置分开来写,因为它们有着一个先后顺序

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**

  • 扫描 mybatis 的接口
  • @author zxj

*/
@Configuration
// 因为这个对象的扫描,需要在 MyBatisConfig 的后面注入,所以加上下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer
= new MapperScannerConfigurer();
//获取之前注入的 beanName 为 sqlSessionFactory 的对象
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//指定 xml 配置文件的路径
mapperScannerConfigurer.setBasePackage("com.framework.msg.mapper");
return mapperScannerConfigurer;
}
}

 

 

然后这就是配置完了,真的很简单,但是细心的朋友可能会问,代码里面怎么没有配置 MyBatis 接口的地址呢?

 

在这里,使用 @Mapper 注解来标识一个接口为 MyBatis 的接口,MyBatis 会自动寻找这个接口,如下

import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface TestDao {

@Select(</span>"select * from wx_userinfo;"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Map&lt;String,Object&gt;<span style="color: rgba(0, 0, 0, 1)"> find();

@Insert(</span>"insert into wx_userinfo(openid,status,nickname,sex,city,province,country,headimgurl,subscribe_time) "+
        "values(#{id},1,'nick',1,'city','provi','contr','img',now())"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> insert(@Param("id")<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id);

}

 

这样就可以使用了,当然,在这之前,你得开启 @ComponentScan 注解,或者直接使用 @SpringBootApplication(推荐)



感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接