SpringBoot+Mybatis整合搭建
本部落格介紹一下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); } }
萬用字元別名掃描
這裡需要注意一點,因為專案業務需要,這裡的別名掃描是做到了竟然萬用字元的,詳情可以參考我之前的部落格:https://blog.csdn.net/u014427391/article/details/84723292
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>
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); returnitemDetail; } }
程式碼取自個人的開源專案:https://github.com/u014427391/taoshop ,有需要可以參考