在这篇文章(http://www.jianshu.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、在浏览器中输入路径访问,结果如下: