Spring boot怎么整合Mybatis
最近剛接觸spring boot,正是因?yàn)樗募昂喤渲梅奖汩_發(fā),促使我下定決心要用它把之前寫的項(xiàng)目重構(gòu),那么問題來了,spring boot怎么整合mybatis呢,下面幾個(gè)配置類來搞定。
在我的代碼當(dāng)中是實(shí)現(xiàn)了數(shù)據(jù)庫讀寫分離的,所以代碼僅做參考,如有需要可以加我微信:benyzhous
【后續(xù)更新】
1、文件結(jié)構(gòu)
DataBaseConfiguration.Java用來獲取數(shù)據(jù)庫連接配置信息,配置從application.properties中讀取
MybatisConfiguration.java也就是MyBatis配置核心入口,構(gòu)建連接創(chuàng)建SqlSessionFactory
2、下面直接貼代碼,有問題的話可以留言或者加我的微信公眾號(hào):cha-baba,或者個(gè)人微信號(hào):benyzhous
application.yml 相關(guān)配置
# Server settings server: port:8080 address:localhost # DATASOURCE jdbc: driverClass: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/local-kaishustory?useUnicode=true&characterEncoding=utf-8 username: root password: root # SPRING PROFILES spring: # HTTP ENCODING http: encoding.charset: UTF-8 encoding.enable: true encoding.force: true # WeiXin Configuration weixin: mp: appid: xx secret: ee token: weixin aeskey: # MyBatis mybatis: typeAliasesPackage: com.modou.**.domain mapperLocations: classpath:/com/modou/**/mapper/*.xml configLocation: classpath:/mybatis-config.xml # LOGGING logging: level: com.ibatis:DEBUG
DataBaseConfiguration.java
package com.modou.conf.mybatis; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.alibaba.druid.pool.DruidDataSource; @Configuration @EnableTransactionManagement public class DataBaseConfiguration implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class); @Override public void setEnvironment(Environment env) { this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc."); } @Bean(name="writeDataSource", destroyMethod = "close", initMethod="init") @Primary public DataSource writeDataSource() { log.debug("Configruing Write DataSource"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driverClassName")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); return datasource; } @Bean(name="readOneDataSource", destroyMethod = "close", initMethod="init") public DataSource readOneDataSource() { log.debug("Configruing Read One DataSource"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driverClassName")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); return datasource; } @Bean(name="readTowDataSource", destroyMethod = "close", initMethod="init") public DataSource readTowDataSource() { log.debug("Configruing Read Two DataSource"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driverClassName")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); return datasource; } @Bean(name="readDataSources") public List<DataSource> readDataSources(){ List<DataSource> dataSources = new ArrayList<DataSource>(); dataSources.add(readOneDataSource()); dataSources.add(readTowDataSource()); return dataSources; } }
MyBatisConfiguration.java
package com.modou.conf.mybatis; import java.util.List; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.plugin.rw.RoundRobinRWRoutingDataSourceProxy; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * * 獲取第二個(gè)數(shù)據(jù)庫的連接信息,在application.yml中配置,并指定特定的前綴 * */ @Configuration @ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class }) @AutoConfigureAfter({ DataBaseConfiguration.class }) @MapperScan(basePackages={"com.modou.**.mapper","com.github.abel533.entity.mapper"}) public class MybatisConfiguration implements EnvironmentAware{ private static Log logger = LogFactory.getLog(MybatisConfiguration.class); private RelaxedPropertyResolver propertyResolver; @Resource(name="writeDataSource") private DataSource writeDataSource; @Resource(name="readDataSources") private List<Object> readDataSources; @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis."); } @Bean @ConditionalOnMissingBean public SqlSessionFactory sqlSessionFactory() { try { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(roundRobinDataSouceProxy()); sessionFactory.setTypeAliasesPackage(propertyResolver .getProperty("typeAliasesPackage")); sessionFactory .setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(propertyResolver .getProperty("mapperLocations"))); sessionFactory .setConfigLocation(new DefaultResourceLoader() .getResource(propertyResolver .getProperty("configLocation"))); return sessionFactory.getObject(); } catch (Exception e) { logger.warn("Could not confiure mybatis session factory"); return null; } } @Bean public RoundRobinRWRoutingDataSourceProxy roundRobinDataSouceProxy(){ RoundRobinRWRoutingDataSourceProxy proxy = new RoundRobinRWRoutingDataSourceProxy(); proxy.setWriteDataSource(writeDataSource); proxy.setReadDataSoures(readDataSources); proxy.setReadKey("READ"); proxy.setWriteKey("WRITE"); return proxy; } @Bean @ConditionalOnMissingBean public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(writeDataSource); } }
Application.java
package com.modou.weixin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.modou.weixin.service.HelloWorldService; /** * Created by chababa on 15/8/22. */ @Configuration @ComponentScan(basePackages={"com.modou.conf","com.modou.weixin"}) @EnableAutoConfiguration public class Application implements CommandLineRunner{ @Autowired HelloWorldService helloWorldService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { System.out.println(this.helloWorldService.print()); } }
3、maven pom.xml 相關(guān)依賴[我是基于我的多模塊依賴,這里只是一個(gè)示意],其中配置了jrebel熱部署插件,需要搭配jrebel6.2.1,具體配置和下載請(qǐng)轉(zhuǎn)向 http://blog.csdn.net/xiaoyu411502/article/details/48047369
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.modou.weixin</groupId> <artifactId>weixin-boot-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../weixin-boot-parent</relativePath> </parent> <artifactId>weixin-boot-services</artifactId> <name>weixin-boot-services</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <springloaded.version>1.2.4.RELEASE</springloaded.version> </properties> <dependencies> <dependency> <groupId>com.modou.weixin</groupId> <artifactId>weixin-boot-sdk</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.modou.weixin</groupId> <artifactId>mybatis-plugin-rw</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> </dependency> </dependencies> </project>
以上所述是小編給大家介紹的Spring boot整合Mybatis的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Java正則表達(dá)式_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
什么是正則表達(dá)式,正則表達(dá)式的作用是什么?這篇文章主要為大家詳細(xì)介紹了Java正則表達(dá)式的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05Spring Cache的基本使用與實(shí)現(xiàn)原理詳解
緩存是實(shí)際工作中非經(jīng)常常使用的一種提高性能的方法, 我們會(huì)在很多場景下來使用緩存。下面這篇文章主要給大家介紹了關(guān)于Spring Cache的基本使用與實(shí)現(xiàn)原理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-05-05Java的Lambda表達(dá)式和Stream流的作用以及示例
這篇文章主要介紹了Java的Lambda表達(dá)式和Stream流簡單示例,Lambda允許把函數(shù)作為一個(gè)方法的參數(shù),使用Lambda表達(dá)式可以寫出更簡潔、更靈活的代碼,而其作為一種更緊湊的代碼風(fēng)格,使Java的語言表達(dá)能力得到了提升,需要的朋友可以參考下2023-05-05springmvc+mybatis 做分頁sql 語句實(shí)例代碼
本文通過一段實(shí)例代碼給大家介紹了springmvc+mybatis 做分頁sql 語句的方法,代碼簡單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-07-07spring MVC + bootstrap實(shí)現(xiàn)文件上傳示例(帶進(jìn)度條)
本篇文章主要介紹了spring MVC + bootstrap實(shí)現(xiàn)文件上傳示例(帶進(jìn)度條),非常具有使用價(jià)值,有需要的朋友可以了解一下。2017-03-03