@Author Jack Wang
轉(zhuǎn)載請注明出處,http://www.reibang.com/p/8138ccd0d900
Spring Boot 集成MyBatis有兩種方式,一種簡單的方式就是使用MyBatis官方提供的:mybatis-spring-boot-starter
另外一種方式就是仍然用類似mybatis-spring的配置方式听想,這種方式需要自己寫一些代碼腥刹,但是可以很方便的控制MyBatis的各項配置。
2018.09.10 , 第一次更新
一:mybatis-spring-boot-starter方式【推薦】
1.1 創(chuàng)建Maven工程,搭建包結(jié)構(gòu)
或者使用springboot initializer自動創(chuàng)建工程, http://start.spring.io/
1.2 構(gòu)建環(huán)境,使用mybatis generatorConfig插件自動生成entity及mapper
generatorConfig.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<classPathEntry
location="D:\repositories\repository_hh\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar" />
<context id="generator-code">
<commentGenerator>
<!-- 是否去除自動生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/license_system?characterEncoding=utf8" userId="root"
password="jacky" />
<javaModelGenerator targetPackage="com.dream.mybatis.entity"
targetProject="springboot-mybatis/src/main/java" />
<sqlMapGenerator targetPackage="com.dream.mybatis.mapper"
targetProject="springboot-mybatis/src/main/resources" />
<javaClientGenerator targetPackage="com.dream.mybatis.dao"
targetProject="springboot-mybatis/src/main/java" type="XMLMAPPER" />
<table tableName="t_equipment" domainObjectName="Equipment"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_department" domainObjectName="Department"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_employee" domainObjectName="Employee"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_license" domainObjectName="License"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_project" domainObjectName="Project"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_project_detail" domainObjectName="ProjectDetail"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_project_license_asso" domainObjectName="ProjectLicenseAsso"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
<table tableName="t_warehouse" domainObjectName="Warehouse"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
注意mysql的jar包及數(shù)據(jù)庫連接屬性以及表格要與實際情況一一對應(yīng)汉买。
mybatis-generator插件在eclipse market商店搜索插件下載即可衔峰。右鍵generatorConfig.xml運行插件就可以自動生成。
1.3 pom添加Maven依賴蛙粘,properties中添加配置
pom :
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 熱部署插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>true</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
================================================================================
application.properties :
spring.datasource.url=jdbc:mysql://localhost:3306/license_system
spring.datasource.username=root
spring.datasource.password=jacky
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml
***注意:這里mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml是配置mapper.xml的路徑的垫卤。
確保路徑正確,并且xml中namespace對應(yīng)的Mapper接口無誤,否則可能會報異常:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.dream.mybatis.dao.WarehouseMapper.insert
1.4 Springboot啟動入口Application
@SpringBootApplication
@MapperScan("com.dream.mybatis.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注意:這里配置的@MapperScan("xx.xx.xx")是配置Mapper接口的位置,確保位置對應(yīng)正確
到這里springboot集成mybatis就已經(jīng)結(jié)束了出牧,真正需要我們進行配置的只有幾點:
1. 添加maven依賴穴肘。mybatis-spring-boot-starter及mysql驅(qū)動
2. 配置application.properties中mapper.xml的位置。mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml
3. Application.java中Mapper接口的位置舔痕。@MapperScan("com.dream.mybatis.dao")
事務(wù)的支持還和平常使用一樣,在Service上添加@Transactional注解即可评抚。
@Service
@Transactional
public class WarehouseServiceImpl implements WarehouseService {
@Autowired
private WarehouseMapper warehouseMapper;
@Override
public void insert() {
Warehouse record = new Warehouse();
record.setId(888L);
record.setName("測試回滾");
warehouseMapper.insert(record);
int i = 1/0;
}
}
二、mybatis-spring方式
2.1 創(chuàng)建Maven工程,搭建包結(jié)構(gòu)
包結(jié)構(gòu)與方式一一樣
2.2 構(gòu)建環(huán)境,使用mybatis generatorConfig插件自動生成entiry及mapper(略)
2.3 pom添加Maven依賴,properties中添加配置
1. pom中添加的依賴與方式一不同,這里是使用mybatis-spring依賴進行集成
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 熱部署插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>true</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
-------------------------------------------------------------------------------------------------
2. application.properties只需要添加springboot數(shù)據(jù)庫連接的配置即可
spring.datasource.url=jdbc:mysql://localhost:3306/license_system
spring.datasource.username=root
spring.datasource.password=jacky
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.4 MyBatis配置類
import java.util.Properties;
import javax.sql.DataSource;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import com.github.pagehelper.PageHelper;
@SpringBootConfiguration
@MapperScan({"invengo.cn.base.mapper"})
@AutoConfigureAfter(DBConfiguration.class)
public class MyBatisConfig implements TransactionManagementConfigurer {
// Springboot根據(jù)properties自動完成配置的DataSource
@Autowired
private DataSource dataSource;
@Bean
public SqlSessionFactory sqlSessionFactoryBean(PageHelper pageHelper) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/*.xml"));
// sqlSessionFactoryBean.setPlugins(new Interceptor[] { pageHelper });
return sqlSessionFactoryBean.getObject();
}
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
// 分頁支持
/*@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
properties.setProperty("dialect", "mysql"); // 配置mysql數(shù)據(jù)庫的方言
pageHelper.setProperties(properties);
return pageHelper;
}*/
}
注意:
1. @MapperScan("com.dream.mybatis.dao")用于掃描Mapper接口,注意路徑
2. sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/*.xml"));用于配置mapper.xml的路徑
3. 注釋的部分為使用該方式時對PageHelper插件的支持,后面章節(jié)會使用到PageHelper插件
事務(wù)的支持還和平常使用一樣,在Service上添加@Transactional注解即可伯复。
2.5 Application啟動類
@SpringBootApplication
public class PayApplication {
private static Logger logger = Logger.getLogger(PayApplication.class);
public static void main(String[] args) {
SpringApplication.run(PayApplication.class, args);
logger.info("SpringBoot Start Success");
}
}