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 {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class,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 public BasicDataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(maxActive); dataSource.setMaxIdle(maxIdel); dataSource.setMaxWait(maxWait); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestOnBorrow(true); return 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
    public PlatformTransactionManager annotationDrivenTransactionManager() {
         return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new 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("select * from wx_userinfo;")
    public Map<String,Object> find();
    
    @Insert("insert into wx_userinfo(openid,status,nickname,sex,city,province,country,headimgurl,subscribe_time) "+
            "values(#{id},1,'nick',1,'city','provi','contr','img',now())")
    public int insert(@Param("id")int id);
}

 

這樣就可以使用了,當然,在這之前,你得開啟@ComponentScan注解,或者直接使用@SpringBootApplication(推薦)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM