在這篇文章(http://www.lxweimin.com/p/483841e4b7d5)中創建的spring boot項目基礎上,進行mybatis整合。
1、引入相關依賴包:
<!-- 連接MySQL數據庫 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis相關包 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.3</version>
</dependency>
<!-- Spring對JDBC數據訪問進行封裝的所有類 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- 數據庫連接池相關 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、在application.yml中spring節點下添加數據庫配置:
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
username: root
password: beibei
url: jdbc:mysql://123.207.188.73:3306/beibeiDoc?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
initialSize: 5
minIdle: 5
maxActive: 30
maxWait: 60000
showsql: true
注意:如果是版本號比較高的數據庫,url后面一定要加上 useSSL=false
3、創建DBProperties.java類,用來讀取數據庫配置:
package com.beibei.doc.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 數據庫配置
* @author beibei
*
*/
@Component // 必須要有這個注解,否則無法在其他地方自動注入
@ConfigurationProperties(prefix="spring.datasource")//此處表示只讀取application.yml中spring下面的datasource下面的屬性
public class DBProperties {
//各個屬性名稱和application.yml中spring.datasource下面的各個屬性key一一對應
private String driverClassName;
private String url;
private String username;
private String password;
private String initialSize;
private String minIdle;
private String maxActive;
private String maxWait;
private String showsql;
//為了節省篇幅,此處略去getter、setter方法
}
4、創建DataBaseConfig.java類,以配置數據庫連接池、事務管理、
加載mapper.xml文件等,要注意各種注解的使用,類名隨意。
package com.beibei.doc.config;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.beibei.doc.config.properties.DBProperties;
/**
*
* @author beibei
*
*/
@Configuration
@ComponentScan({
"com.beibei.doc.*.controller",
"com.beibei.doc.*.service"
})
@MapperScan({"com.beibei.doc.dao.*","com.beibei.doc.dao.*.ext"}) //dao層類所在包
@EnableTransactionManagement
@EnableScheduling
@EnableAsync
public class DataBaseConfig {
/**自動注入數據庫配置類*/
@Autowired
private DBProperties db;
/**
* 構建數據源
* @return
*/
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(db.getDriverClassName());
dataSource.setUrl(db.getUrl());
dataSource.setUsername(db.getUsername());
dataSource.setPassword(db.getPassword());
// 配置初始化大小、最小、最大
dataSource.setInitialSize(Integer.valueOf(db.getInitialSize()));
dataSource.setMinIdle(Integer.valueOf(db.getMinIdle()));
dataSource.setMaxActive(Integer.valueOf(db.getMaxActive()));
// 配置獲取連接等待超時的時間
dataSource.setMaxWait(Long.valueOf(db.getMaxWait()));
//配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(60000);
//配置一個連接在池中最小生存的時間,單位是毫秒
dataSource.setMinEvictableIdleTimeMillis(300000);
//打開PSCache,并且指定每個連接上PSCache的大小
//dataSource.setPoolPreparedStatements(true);
//dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
//禁用對于長時間不使用的連接強制關閉的功能
dataSource.setRemoveAbandoned(false);
try {
WallConfig wc=new WallConfig();
wc.setMultiStatementAllow(true);
WallFilter wf=new WallFilter();
wf.setConfig(wc);
List<Filter> filters = new ArrayList<>();
filters.add(wf);
dataSource.setFilters("stat,wall");
dataSource.setProxyFilters(filters);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public SqlSessionFactory sqlSessionFactory(){
SqlSessionFactory factory = null;
try {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
//讀取mybatis各個類的 *mapper.xml文件,這個地方的locationPattern一定要寫對,不然會找不到輸出到target\classes\mybatis\*目錄下的mapper.xml文件
String locationPattern = "classpath*:/mybatis/*/*.xml";
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(locationPattern);
List<Resource> filterResourceList = new ArrayList<Resource>();
List<String> fileNameList = new ArrayList<String>();
for (int i=0; i<resources.length; i++){
Resource resource = resources[i];
if(!fileNameList.contains(resource.getFilename())){
filterResourceList.add(resource);
fileNameList.add(resource.getFilename());
}
}
Resource[] result = new Resource[filterResourceList.size()];
sessionFactoryBean.setMapperLocations(filterResourceList.toArray(result));
factory = (SqlSessionFactory) sessionFactoryBean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return factory;
}
@Bean
public AsyncConfigurerSupport configurerSupport(){
return new AsyncConfigurerSupport(){
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(50000);
executor.setThreadNamePrefix("DocThreadPool");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return super.getAsyncUncaughtExceptionHandler();
}
};
}
}
5、創建一張數據庫表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(20) DEFAULT NULL COMMENT '用戶名',
`password` varchar(100) DEFAULT NULL COMMENT '密碼',
`age` int(3) DEFAULT NULL COMMENT '年齡',
`sex` varchar(1) DEFAULT NULL COMMENT '性別',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
插入一條數據
6、用相關工具生成該表對應的User.java類,UserExample.java類以及UserMapper.xml文件。這些文件放置目錄如下圖:
其中UserMapper.xml生成后記得要把其命名空間改成UserMapper.java的類全名稱,
其中引用到User.java、UserExample.java也要使用全名稱:
7、創建BaseMapper.java類,該類中各個方法名稱和mapper.xml中各個select的id相同:
package com.beibei.doc.dao.base;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* dao層基類
* @author beibei
*
* @param <M> 實體類
* @param <E> 實體類對應的mapper
*/
public interface BaseMapper<M, E> {
public int countByExample(E example);
public int deleteByExample(E example);
public int deleteByPrimaryKey(Integer id);
public int insert(M record);
public int insertSelective(M record);
public List<M> selectByExample(E example);
public M selectByPrimaryKey(Integer id);
public int updateByExampleSelective(@Param("record") M record, @Param("example") E example);
public int updateByExample(@Param("record") M record, @Param("example") E example);
public int updateByPrimaryKeySelective(M record);
public int updateByPrimaryKey(M record);
}
創建UserMapper.java繼承BaseMapper.java。(因為兩個類都是接口)
package com.beibei.doc.dao.user;
import com.beibei.doc.dao.base.BaseMapper;
import com.beibei.doc.model.user.User;
import com.beibei.doc.model.user.UserExample;
public interface UserMapper extends BaseMapper<User, UserExample> {
}
8、構建service層基類:
創建BaseService.java接口文件
package com.beibei.doc.service.base;
import java.util.List;
/**
* service基類實現類
* @author beibei
*
* @param <M> 實體類
* @param <E> 對應的mapper類
*/
public interface BaseService<M, E> {
/**
* 通過id獲取數據
* @param id
* @return
* @throws RuntimeException
*/
public M selectByPrimaryKey(Integer id) throws RuntimeException;
/**
* 根據Example類進行查詢
* @param example
* @return
* @throws RuntimeException
*/
public List<M> selectByExample(E example) throws RuntimeException;
/**
* 根據主鍵刪除
* @param id
* @throws RuntimeException
*/
public int deleteByPrimaryKey(Integer id) throws RuntimeException;
/**
* 根據Example類進行刪除
* @param example
* @throws RuntimeException
*/
public int deleteByExample(E example) throws RuntimeException;
/**
* 插入數據(全值)
* @param model
* @throws RuntimeException
*/
public int insert(M model) throws RuntimeException;
/**
* 插入數據(非空值)
* @param model
* @throws Exception
*/
public int insertSelective(M model) throws Exception;
/**
* 根據Example類查詢數量
* @param k
* @return
* @throws RuntimeException
*/
public Integer countByExample(E example) throws RuntimeException;
/**
*/
public int updateByExampleSelective(M model, E example) throws RuntimeException;
/**
* 根據Example類更新對象
* @param model 更新模版
* @param example Example類
* @throws RuntimeException
*/
public int updateByExample(M model, E example) throws RuntimeException;
/**
* 根據主鍵更新對象(非空)
* @param model
* @throws RuntimeException
*/
public int updateByPrimaryKeySelective(M model) throws RuntimeException;
/**
* 根據主鍵更新對象
* @param model
* @throws RuntimeException
*/
public int updateByPrimaryKey(M model) throws RuntimeException;
}
創建實現類BaseServiceImpl.java
package com.beibei.doc.service.base.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.beibei.doc.dao.base.BaseMapper;
import com.beibei.doc.service.base.BaseService;
/**
* service層基類
* @author beibei
*
* @param <M>
* @param <E>
*/
public class BaseServiceImpl<M, E> implements BaseService<M, E> {
@Autowired
protected BaseMapper<M, E> baseMapper;
@Transactional(readOnly = true)
public M selectByPrimaryKey(Integer id) throws RuntimeException {
return baseMapper.selectByPrimaryKey(id);
}
@Transactional(readOnly = true)
public List<M> selectByExample(E example) throws RuntimeException {
return baseMapper.selectByExample(example);
}
public int deleteByPrimaryKey(Integer id) throws RuntimeException {
return baseMapper.deleteByPrimaryKey(id);
}
public int deleteByExample(E example) throws RuntimeException {
return baseMapper.deleteByExample(example);
}
public int insert(M model) throws RuntimeException {
return baseMapper.insert(model);
}
public int insertSelective(M model) throws RuntimeException {
return baseMapper.insertSelective(model);
}
public Integer countByExample(E example) throws RuntimeException {
return baseMapper.countByExample(example);
}
public int updateByExampleSelective(M model, E example) throws RuntimeException {
return baseMapper.updateByExampleSelective(model, example);
}
public int updateByExample(M model, E example) throws RuntimeException {
return baseMapper.updateByExample(model, example);
}
public int updateByPrimaryKeySelective(M model) throws RuntimeException {
return baseMapper.updateByPrimaryKeySelective(model);
}
public int updateByPrimaryKey(M model) throws RuntimeException {
return baseMapper.updateByPrimaryKey(model);
}
}
這兩個類是提取了公共方法的基類,和BaseMapper.java中各個方法一致。
9、創建Service層各個實體類對應的Service類,下面是分別創建UserService.java接口和其實現類UserServiceImpl.java。
UserService.java
package com.beibei.doc.service.user;
import com.beibei.doc.model.user.User;
import com.beibei.doc.model.user.UserExample;
import com.beibei.doc.service.base.BaseService;
public interface UserService extends BaseService<User, UserExample> {
}
UserServiceImpl.java
package com.beibei.doc.service.user.impl;
import org.springframework.stereotype.Service;
import com.beibei.doc.model.user.User;
import com.beibei.doc.model.user.UserExample;
import com.beibei.doc.service.base.impl.BaseServiceImpl;
import com.beibei.doc.service.user.UserService;
@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserExample> implements UserService {
}
這樣子UserService就有了基礎的增刪改查方法了,如果需要添加其他業務操作方法,就直接在UserService.java中添加接口,并且在UserServiceImpl.java中實現就可以了。
10、在HelloController.java中編輯接口代碼,調用service層業務方法:
package com.beibei.doc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.beibei.doc.model.user.User;
import com.beibei.doc.service.user.UserService;
@RestController
@RequestMapping("/hello")
public class HelloConrtoller {
@Autowired
private UserService userService;
@RequestMapping(value="/say")
public String say(){
User user = userService.selectByPrimaryKey(1);
if(user == null){
return null;
}
return user.getUsername() + ", 年齡=" + user.getAge();
}
}
11、在瀏覽器中輸入路徑訪問,結果如下: