本部落格介紹一下SpringBoot內建Mybatis,資料庫連接配接池使用alibaba的druid,使用SpringBoot微架構雖然內建Mybatis之後可以不使用xml的方式來寫sql,但是用慣了xml的其實也可以用xml來實作的,實作上具體用什麼方式并不重要,主要是搭建一遍,對架構的運轉就比較清晰。本部落格還是用xml的方式來實作Mybatis的sql編寫,不用注解方式。
maven配置
<!-- springboot mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
當然要引入druid,mysql等等jar的話可以參考我一個項目裡的parent工程的maven配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.muses.taoshop</groupId>
<artifactId>taoshop</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>taoshop</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 子產品版本 -->
<taoshop-web-portal.version>1.0</taoshop-web-portal.version>
<!-- 外部依賴 -->
<log4j.version>1.2.17</log4j.version>
<mysql.version>5.1.27</mysql.version>
<mybatis.version>3.4.0</mybatis.version>
<mybatis.spring.version>1.3.0</mybatis.spring.version>
<mybatis.springboot.version>1.3.1</mybatis.springboot.version>
<mysql-connector.version>5.1.39</mysql-connector.version>
<spring-boot.version>1.5.7.RELEASE</spring-boot.version>
<druid.version>1.1.2</druid.version>
<github.pagehelper.version>4.2.1</github.pagehelper.version>
<fastjson.version>1.2.7</fastjson.version>
<lombok.version>1.16.10</lombok.version>
</properties>
<modules>
<module>taoshop-quartz</module>
<module>taoshop-search</module>
<module>taoshop-common</module>
<module>taoshop-provider-api</module>
<module>taoshop-provider</module>
<module>taoshop-manager</module>
<module>taoshop-portal</module>
<module>taoshop-cms</module>
<module>taoshop-order</module>
<module>taoshop-sso</module>
</modules>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!-- 設定源檔案編譯 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerVersion>1.8</compilerVersion>
<encoding>UTF-8</encoding>
<skipMain></skipMain>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<!-- 解決資源檔案的編碼問題 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- springboot mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.springboot.version}</version>
</dependency>
<!-- 熱部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- alibaba druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- Themeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${github.pagehelper.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- 其他工具包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
</dependencies>
<!-- 設定Maven主倉庫為阿裡私服 -->
<repositories>
<repository>
<id>repos</id>
<name>Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
</repositories>
<!-- 設定插件倉庫 -->
<pluginRepositories>
<pluginRepository>
<id>pluginsRepos</id>
<name>PluginsRepository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</pluginRepository>
</pluginRepositories>
</project>
SpringBoot配置檔案
server:
port: 8081
#logging:
# config: classpath:logback_spring.xml.bat
# level:
# com.muses.taoshop: debug
# path: /data/logs
spring:
datasource:
# 主資料源
shop:
url: jdbc:mysql://127.0.0.1:3306/taoshop?autoReconnect=true&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 連接配接池設定
druid:
initial-size: 5
min-idle: 5
max-active: 20
# 配置擷取連接配接等待逾時的時間
max-wait: 60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒
time-between-eviction-runs-millis: 60000
# 配置一個連接配接在池中最小生存的時間,機關是毫秒
min-evictable-idle-time-millis: 300000
# Oracle請使用select 1 from dual
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打開PSCache,并且指定每個連接配接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用于防火牆
filters: stat,wall,slf4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多個DruidDataSource的監控資料
use-global-data-source-stat: true
# jpa:
# database: mysql
# hibernate:
# show_sql: true
# format_sql: true
# ddl-auto: none
# naming:
# physical-strategy: org.hibernate.boot.entity.naming.PhysicalNamingStrategyStandardImpl
# mvc:
# view:
# prefix: /WEB-INF/jsp/
# suffix: .jsp
#添加Thymeleaf配置
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
content-type: text/html
#Jedis配置
# jedis :
# pool :
# host : 127.0.0.1
# port : 6379
# password : redispassword
# timeout : 0
# config :
# maxTotal : 100
# maxIdle : 10
# maxWaitMillis : 100000
Application啟動類
package com.muses.taoshop;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;
/**
*
* <pre>
* SpringBoot啟動配置類
* </pre>
* @author nicky
* @version 1.00.00
* <pre>
* 修改記錄
* 修改後版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
@Controller
@EnableScheduling//開啟對計劃任務的支援
@EnableTransactionManagement//開啟對事務管理配置的支援
@EnableCaching
@EnableAsync//開啟對異步方法的支援
@EnableAutoConfiguration
@ServletComponentScan
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,
MybatisAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
public class PortalApplication {
@RequestMapping("/")
@ResponseBody
String home() {
return "portal web!";
}
@RequestMapping("/doTest")
@ResponseBody
String doTest(){
System.out.println(Thread.currentThread().getName());
String threadName = Thread.currentThread().getName();
return threadName;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(PortalApplication.class, args);
}
}
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,
MybatisAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class}),這個注釋是必須的,開啟自動掃描資料源和Mybatis配置檔案
資料庫配置
做好SpringBoot啟動類的注解之後,需要編寫Mybatis和資料源的配置類
寫一個Constants類:
package com.muses.taoshop.common.core.database.config;
/**
* <pre>
* 基本配置類
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改記錄
* 修改後版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
public class BaseConfig {
/**
* 設定主資料源名稱
*/
public static final String DATA_SOURCE_NAME = "shop";
/**
* 加載配置檔案資訊
*/
public static final String DATA_SOURCE_PROPERTIES = "spring.datasource.shop";
/**
* repository 所在包
*/
public static final String REPOSITORY_PACKAGES = "com.muses.taoshop.**.repository";
/**
* mapper 所在包
*/
public static final String MAPPER_PACKAGES = "com.muses.taoshop.**.mapper";
/**
* 實體類 所在包
*/
public static final String ENTITY_PACKAGES = "com.muses.taoshop.*.entity";
/**
* 自定義TypeHandler
*/
public static final String TYPE_HANDLERS_PACKAGES = "com.muses.taoshop.common.core.database.typehandlers";
/**
* Mybatis session 工廠
*/
public static final String SQL_SESSION_FACTORY = "sqlSessionFactory";
/**
* Mybatis 事務管理器
*/
public static final String MYBATIS_TRANSACTION_MANAGER = "mybatisTransactionManager";
/**
* Jedis連接配接池
*/
public static final String JEDIS_POOL = "jedisPool";
/**
* Jedis連接配接池配置
*/
public static final String JEDIS_POOL_CONFIG = "jedisPoolConfig";
}
DataSource配置類:
package com.muses.taoshop.common.core.database.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import static com.muses.taoshop.common.core.database.config.BaseConfig.DATA_SOURCE_NAME;
import static com.muses.taoshop.common.core.database.config.BaseConfig.DATA_SOURCE_PROPERTIES;
/**
* <pre>
* DataSource配置類
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改記錄
* 修改後版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
@Configuration
public class DataSourceConfig {
@Bean(name = DATA_SOURCE_NAME)
@ConfigurationProperties(prefix = DATA_SOURCE_PROPERTIES)
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
}
Mybatis配置類:
package com.muses.taoshop.common.core.database.config;
//import com.muses.taoshop.common.core.database.annotation.MybatisRepository;
import com.muses.taoshop.common.core.database.annotation.TypeAliasesPackageScanner;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import static com.muses.taoshop.common.core.database.config.BaseConfig.*;
/**
* <pre>
* Mybatis配置類
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改記錄
* 修改後版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
@MapperScan(
basePackages = MAPPER_PACKAGES,
//annotationClass = MybatisRepository.class,
sqlSessionFactoryRef = SQL_SESSION_FACTORY
)
@ComponentScan
@EnableTransactionManagement
@Configuration
public class MybatisConfig {
//@Autowired
//MybatisSqlInterceptor mybatisSqlInterceptor;
TypeAliasesPackageScanner packageScanner = new TypeAliasesPackageScanner();
@Bean(name = DATA_SOURCE_NAME)
@ConfigurationProperties(prefix = DATA_SOURCE_PROPERTIES)
@Primary
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = SQL_SESSION_FACTORY)
public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource)throws Exception{
//SpringBoot預設使用DefaultVFS進行掃描,但是沒有掃描到jar裡的實體類
VFS.addImplClass(SpringBootVFS.class);
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//factoryBean.setPlugins(new Interceptor[]{mybatisSqlInterceptor});
factoryBean.setDataSource(dataSource);
//factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try{
factoryBean.setMapperLocations(resolver.getResources("classpath*:/mybatis/*Mapper.xml"));
String typeAliasesPackage = packageScanner.getTypeAliasesPackages();
factoryBean.setTypeAliasesPackage(typeAliasesPackage);
SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
return sqlSessionFactory;
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException();
}
}
@Bean(name = MYBATIS_TRANSACTION_MANAGER)
public DataSourceTransactionManager transactionManager(@Qualifier(DATA_SOURCE_NAME)DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
通配符别名掃描
這裡需要注意一點,因為項目業務需要,這裡的别名掃描是做到了竟然通配符的,詳情可以參考我之前的部落格
Mybatis例子實踐
是以,SpringBoot內建Mybatis就基本搭建好了,下面來實踐一個例子:
注意:Mybatis的xml檔案都要放在resources資源檔案夾下面的一個Mybatis檔案夾裡面,因為已經做了配置
factoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/Mapper.xml"));
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.muses.taoshop.item.mapper.ItemMapper" >
<sql id="BaseColumnList" >
id ,
sku_code ,
sku_name ,
price ,
stock ,
last_modify_time as lastModifyTime,
create_time as createTime
</sql>
<sql id="OrderBy">
ORDER BY price
</sql>
<!-- 商品詳情-->
<select id="getItemDetail" resultType="ItemDetail">
SELECT
itb.brand_name AS brandName,
s.shop_name AS shopName,
spu.item_name AS itemName,
sku.price,
sku.promotion_price AS promotionPrice,
sku.img_path AS imgPath,
sku.stock
FROM
item_spu spu
RIGHT JOIN item_brand itb
ON itb.id = spu.brand_id
RIGHT JOIN shop_info s
ON s.id = spu.shop_id
LEFT JOIN
(SELECT
s.price,
s.promotion_price,
s.spu_id,
s.img_path,
s.stock
FROM
item_sku s
GROUP BY s.spu_id) sku
ON sku.spu_id = spu.id
<where>
spu.id = #{spuId}
</where>
</select>
</mapper>
package com.muses.taoshop.item.mapper;
import com.muses.taoshop.item.entity.ItemDetail;
import com.muses.taoshop.item.entity.ItemPortal;
import com.muses.taoshop.item.entity.ItemSpec;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface ItemMapper {
ItemDetail getItemDetail(@Param("spuId")int spuId);
}
package com.muses.taoshop.item.service;
import com.muses.taoshop.item.entity.ItemDetail;
import com.muses.taoshop.item.entity.ItemPortal;
import com.muses.taoshop.item.entity.ItemSpec;
import com.muses.taoshop.item.mapper.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <pre>
* 商品資訊服務實作類
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改記錄
* 修改後版本: 修改人: 修改日期: 2018.06.24 22:37 修改内容:
* </pre>
*/
@Service
public class ItemServiceImpl implements IItemService {
@Autowired
ItemMapper itemMapper;
/**
* 擷取商品詳情資訊
* @return ItemDetail
*/
@Override
public ItemDetail getItemDetailInfo(int spuId){
ItemDetail itemDetail = itemMapper.getItemDetail(spuId);
return itemDetail;
}
}