本例使用mysql作為數(shù)據(jù)庫(kù)针余,使用druid作為數(shù)據(jù)庫(kù)連接池
主要有單數(shù)據(jù)源和多數(shù)據(jù)源實(shí)例;
多數(shù)據(jù)源中又分為:1. 分包形式 2. aop形式 3. 注解形式
項(xiàng)目目錄結(jié)構(gòu)
MyBatis配置實(shí)現(xiàn)
springBoot相比于原來(lái)的Spring的模式就是減少xml配置夺刑,將它們用java代碼實(shí)現(xiàn)。
- DataSource的bean暂幼,主要配置數(shù)據(jù)來(lái)源
- SqlSessionFactoryBean的bean贮泞,引用 datasource,MyBatis配置酬土,sql的xml掃描荆忍,以及各個(gè)插件的添加
- MapperScannerConfigurer的bean的,主要設(shè)置基本掃描包,引用SqlSessionFactoryBean
- DataSourceTransactionManager的bean刹枉,主要用設(shè)置事務(wù)
添加maven依賴
<!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!-- dataSource start -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<!-- dataSource end -->
單數(shù)據(jù)源
基本配置
在application.yml中添加datasource配置:
spring:
application:
name: SpringBoot
datasource:
url: jdbc:mysql://localhost:3306/YanYPro?useUnicode=true&characterEncoding=UTF-8&&useSSL=false
username: root
password: *****
driver-class-name: com.mysql.jdbc.Driver
# 使用druid數(shù)據(jù)源
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小践惑,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置獲取連接等待超時(shí)的時(shí)間
maxWait: 60000
# 配置間隔多久才進(jìn)行一次檢測(cè)嘶卧,檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間凉袱,單位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打開(kāi)PSCache芥吟,并且指定每個(gè)連接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì)专甩,'wall'用于防火墻
filters: stat,wall,log4j
# 通過(guò)connectProperties屬性來(lái)打開(kāi)mergeSql功能钟鸵;慢SQL記錄
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多個(gè)DruidDataSource的監(jiān)控?cái)?shù)據(jù)
useGlobalDataSourceStat: true
配置mybatis-config:
以下只是實(shí)例,可自定義添加一些別的配置
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局參數(shù) -->
<settings>
<!-- 使全局的映射器啟用或禁用緩存涤躲。 -->
<setting name="cacheEnabled" value="true"/>
<!-- 全局啟用或禁用延遲加載棺耍。當(dāng)禁用時(shí),所有關(guān)聯(lián)對(duì)象都會(huì)即時(shí)加載种樱。 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 當(dāng)啟用時(shí)蒙袍,有延遲加載屬性的對(duì)象在被調(diào)用時(shí)將會(huì)完全加載任意屬性。否則嫩挤,每種屬性將會(huì)按需要加載害幅。 -->
<setting name="aggressiveLazyLoading" value="true"/>
<!-- 是否允許單條sql 返回多個(gè)數(shù)據(jù)集 (取決于驅(qū)動(dòng)的兼容性) default:true -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 是否可以使用列的別名 (取決于驅(qū)動(dòng)的兼容性) default:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 允許JDBC 生成主鍵。需要驅(qū)動(dòng)器支持岂昭。如果設(shè)為了true以现,這個(gè)設(shè)置將強(qiáng)制使用被生成的主鍵,有一些驅(qū)動(dòng)器不兼容不過(guò)仍然可以執(zhí)行约啊。 default:false -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 指定 MyBatis 如何自動(dòng)映射 數(shù)據(jù)基表的列 NONE:不隱射 PARTIAL:部分 FULL:全部 -->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<!-- 這是默認(rèn)的執(zhí)行類(lèi)型 (SIMPLE: 簡(jiǎn)單邑遏; REUSE: 執(zhí)行器可能重復(fù)使用prepared statements語(yǔ)句;BATCH: 執(zhí)行器可以重復(fù)執(zhí)行語(yǔ)句和批量更新) -->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!-- 使用駝峰命名法轉(zhuǎn)換字段恰矩。 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 設(shè)置本地緩存范圍 session:就會(huì)有數(shù)據(jù)的共享 statement:語(yǔ)句范圍 (這樣就不會(huì)有數(shù)據(jù)的共享 ) defalut:session -->
<setting name="localCacheScope" value="SESSION"/>
<!-- 設(shè)置但JDBC類(lèi)型為空時(shí),某些驅(qū)動(dòng)程序 要指定值,default:OTHER记盒,插入空值時(shí)不需要指定類(lèi)型 -->
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
</configuration>
代碼實(shí)現(xiàn)
SingleMyBatisConfig的類(lèi)實(shí)現(xiàn)
繼承EnvironmentAware并實(shí)現(xiàn)setEnvironment,為了獲取默認(rèn)配置文件application.yml的元素外傅。
@Configuration
public class SingleMyBatisConfig implements EnvironmentAware{
private final static Logger logger = LoggerFactory.getLogger(SingleMyBatisConfig.class);
private static String MYBATIS_CONFIG = "mybatis-config.xml";
//mybatis mapper resource 路徑
private static String MAPPER_PATH = "classpath:/com/yany/mapper/single/**.xml";
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
}
.......
}
添加@Bean(name = "singleDataSource")孽鸡,設(shè)置實(shí)現(xiàn)DataSource的bean
/**
* @return
* @Primary 優(yōu)先方案,被注解的實(shí)現(xiàn)栏豺,優(yōu)先被注入
*/
@Primary
@Bean(name = "singleDataSource")
public DataSource singleDataSource() {
logger.info("datasource url:{}", propertyResolver.getProperty("url"));
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));
datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));
datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));
datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));
datasource.setTimeBetweenEvictionRunsMillis(Long.valueOf(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
datasource.setValidationQuery(propertyResolver.getProperty("validationQuery"));
datasource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));
datasource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));
datasource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));
datasource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));
datasource.setMaxPoolPreparedStatementPerConnectionSize(Integer.valueOf(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
try {
datasource.setFilters(propertyResolver.getProperty("filters"));
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
}
添加@Bean(name = "singleSqlSessionFactory")彬碱,設(shè)置實(shí)現(xiàn)SqlSessionFactoryBean
/**
* 創(chuàng)建sqlSessionFactory實(shí)例
*
* @return
*/
@Bean(name = "singleSqlSessionFactory")
@Primary
public SqlSessionFactoryBean createSqlSessionFactoryBean(@Qualifier("singleDataSource") DataSource singleDataSource) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//設(shè)置mybatis configuration 掃描路徑
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
sqlSessionFactoryBean.setDataSource(singleDataSource);
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(MAPPER_PATH));
return sqlSessionFactoryBean;
}
添加@Bean(name = "singleTransactionManager"),設(shè)置實(shí)現(xiàn)事務(wù)DataSourceTransactionManager
/**
* 配置事務(wù)管理器
*/
@Bean(name = "singleTransactionManager")
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("singleDataSource") DataSource singleDataSource) throws Exception {
return new DataSourceTransactionManager(singleDataSource);
}
以上SingleMyBatisConfig的配置完成奥洼,上面主要配置了數(shù)據(jù)源巷疼、SqlSessionFactoryBean、事務(wù)(DataSourceTransactionManager)。還差一個(gè)MapperScannerConfigurer的配置嚼沿。
MapperScannerConfig
本來(lái)主要集中實(shí)現(xiàn)各個(gè)數(shù)據(jù)源的MapperScannerConfigurer
@Configuration
public class MapperScannerConfig {
/**
* 單數(shù)據(jù)源配置
*
* @return
*/
@Bean
public MapperScannerConfigurer createSingleMapperScannerConfigurer() {
System.out.println("singleDataSource");
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.yany.dao.single");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("singleSqlSessionFactory");
return mapperScannerConfigurer;
}
}
以上即為單數(shù)據(jù)源使用配置估盘,而具體的dao層的編寫(xiě)以及sql的xml編寫(xiě)詳情見(jiàn):https://github.com/yany8060/SpringDemo.git
com.yany.dao.single中編寫(xiě)單屬于的到接口
com.yany.mapper.single中編寫(xiě)對(duì)應(yīng)的sql的xml
由于貼了比較多的代碼,在下一篇多數(shù)據(jù)中中將直接類(lèi)比這篇中的代碼
詳情請(qǐng)見(jiàn):https://github.com/yany8060/SpringDemo.git
博客:http://yany8060.xyz