简介
SpringBoot整合MyBatis,我这里使用的是SpringBoot1.4.7。
知识点:
- 1.SpringBoot集成MyBatis
- 2.PageHelper分页插件使用
- 3.MyBatis代码自动生成器集成
- 4.通过自定义转换器formatter日期对象
SpringBoot集成MyBatis
- 1.通过maven方式引入依赖jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.3</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
maven依赖成功加载完后,在工程java源码目录中创建:
config、controller、dao、model、service包以及在资源目录中创建mapper目录。
至于项目包名可自行而定。
- 2.创建配置@Configuration
在config包中分别创建:
DataSourceConfig.java ---数据源配置
DruidDBConfig.java ---数据库连接池DruidDB配置
PageHelperConfig.java ---分页插件配置
DataSourceConfig.java:
import com.github.pagehelper.PageInterceptor;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@MapperScan("com.yu.scloud.baseframe.frame.dao")
@EnableTransactionManagement
public class DataSourceConfig {
private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
@Autowired
private Environment env;
@Autowired
private PageInterceptor pageInterceptor;
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(dataSource);
//该配置非常的重要,如果不将PageInterceptor设置到SqlSessionFactoryBean中,导致分页失效
fb.setPlugins(new Interceptor[]{pageInterceptor});
fb.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package"));
fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
return fb.getObject();
}
}
DruidDBConfig.java :
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DruidDBConfig {
private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
PageHelperConfig.java:
import com.github.pagehelper.PageInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* 分页插件的配置
*/
@Configuration
public class PageHelperConfig {
@Value("${pagehelper.helperDialect}")
private String helperDialect;
@Bean
public PageInterceptor pageInterceptor(){
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", helperDialect);
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}
细心的朋友会发现以上三个配置类中都引用了properties中相关配置参数。
项目中的 application.properties 文件内容如下:
####单点式配置######
server.context-path=/bf
server.port=8002
####数据库相关####
spring.datasource.name=babystore
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/apptest?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=yu123456
#使用druid数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#配置DruidDBConfig连接池
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.maxOpenPreparedStatements=20
#mybatic
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yu.scloud.baseframe.frame.model
mapper.mappers=com.yu.scloud.baseframe.frame.dao
mapper.not-empty=false
mapper.identity=MYSQL
#pagehelper
pagehelper.helperDialect=mysql
-
3.创建数据库表
我们在一个叫做 “apptest” 的数据库中创建一个简单的user表结构。
- 4.创建Entity、dao、以及mapper映射xml文件
在 *.model/ 包中创建实体类 User.java
public class User {
int id;
String email;
String password;
String phone;
String uid;
String username;
//......setter/getter方法省略显示
}
在 *.dao/ 包中创建UserDao.java接口
import com.yu.scloud.baseframe.frame.model.User;
import java.util.List;
public interface UserDao {
int insert(User record);
List<User> selectUsers();
}
在resources/mapper包中创建 UserMapper.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.yu.scloud.baseframe.frame.dao.UserDao" >
<sql id="BASE_TABLE">
user
</sql>
<sql id="BASE_COLUMN">
id,email,password,phone,uid,username
</sql>
<insert id="insert" parameterType="com.yu.scloud.baseframe.frame.model.User">
INSERT INTO
<include refid="BASE_TABLE"/>
<trim prefix="(" suffix=")" suffixOverrides=",">
username,password,
<if test="phone != null">
phone,
</if>
<if test="email != null">
email,
</if>
<if test="uid != null">
uid,
</if>
</trim>
<trim prefix="VALUES(" suffix=")" suffixOverrides=",">
#{username, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR},
<if test="phone != null">
#{phone, jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="uid != null">
#{uid,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="selectUsers" resultType="com.yu.scloud.baseframe.frame.model.User">
SELECT
<include refid="BASE_COLUMN"/>
FROM
<include refid="BASE_TABLE"/>
</select>
</mapper>
- 5.创建Service和Controller使用MyBatis
创建UserService.java接口以及实现类 UserServiceImpl.java
创建MyBatisTestController.java类
UserService.java接口:
import com.yu.scloud.baseframe.frame.model.User;
import java.util.List;
public interface UserService {
int addUser(User user);
List<User> findAllUser(int pageNum, int pageSize);
}
UserServiceImpl.java:
import com.github.pagehelper.PageHelper;
import com.yu.scloud.baseframe.frame.dao.UserDao;
import com.yu.scloud.baseframe.frame.model.User;
import com.yu.scloud.baseframe.frame.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;//这里会报错,但是并不会影响
@Override
public int addUser(User user) {
return userDao.insert(user);
}
/*
* 这个方法中用到了我们开头配置依赖的分页插件pagehelper
* 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public List<User> findAllUser(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
PageHelper.startPage(pageNum, pageSize);
return userDao.selectUsers();
}
}
MyBatisTestController.java:
import com.github.pagehelper.PageHelper;
import com.yu.scloud.baseframe.frame.model.User;
import com.yu.scloud.baseframe.frame.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/user")
public class MyBatisTestController {
@Autowired
private UserService userService;
@ResponseBody
@PostMapping("/add")
public int addUser(User user){
return userService.addUser(user);
}
@ResponseBody
@GetMapping("/all")
public Object findAllUser(
@RequestParam(name = "pageNum", required = false, defaultValue = "1")
int pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "10")
int pageSize){
//开始分页
PageHelper.startPage(pageNum,pageSize);
return userService.findAllUser(pageNum,pageSize);
}
}
ok!至此,SpringBoot集成Mybatis以及使用PageHelper分页插件的例子完成,赶快访问一下controller试一下吧,成功的话会通过mybatis插入数据库user数据也可以获取数据库数据。
这篇文章稍微有点长,不易阅读,下面两个知识点放到另一篇文章中讲解吧。
3.MyBatis代码自动生成器集成
4.通过自定义转换器formatter日期对象
参考 https://blog.csdn.net/Winter_chen001/article/details/80010967
代码自动生成器 https://www.cnblogs.com/hongdada/p/7583625.html