今天整理下自己在整合springboot + mybatisPlus 中遇到的一些小挫折。
项目整体结构图:(请注意:我这里使用的MYSQL 版本为8)
项目整体依赖的pom 文件:
4.0.0
com.zzg
springboot
0.0.1-SNAPSHOT
springboot-mybatisplus
org.springframework.boot
spring-boot-starter-web
junit
junit
3.8.1
test
io.springfox
springfox-swagger2
2.2.2
io.springfox
springfox-swagger-ui
2.2.2
org.springframework.boot
spring-boot-starter-jdbc
com.alibaba
druid
1.1.6
mysql
mysql-connector-java
8.0.11
com.baomidou
mybatisplus-spring-boot-starter
1.0.5
com.baomidou
mybatis-plus
2.1.8
org.apache.velocity
velocity-engine-core
2.0
org.freemarker
freemarker
2.3.23
第一步:集成mybatisplus 核心框架pom.xml
org.springframework.boot
spring-boot-starter-jdbc
com.baomidou
mybatisplus-spring-boot-starter
1.0.5
com.baomidou
mybatis-plus
2.1.8
注意: mybatis-plus 自动的维护了mybatis以及mybatis-spring的依赖,在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑。。。
第二步:集成mybatisplus 代码生成器
org.apache.velocity
velocity-engine-core
2.0
org.freemarker
freemarker
2.3.23
编写mybatisplus 自动生成器MybatisPlusGenerator.java(基于单列模式进行创建)
package com.zzg.springboot.auto;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class MybatisPlusGenerator {
private static MybatisPlusGenerator single = null;
private MybatisPlusGenerator() {
super();
}
private static MybatisPlusGenerator getSingle() {
if(single == null) {
single =new MybatisPlusGenerator();
}
return single;
}
public void autoGeneration() {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root")
.setPassword("123456")
.setDriverName("com.mysql.cj.jdbc.Driver");
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel);
config.setActiveRecord(false)
.setEnableCache(false)
.setAuthor("zzg")
//指定输出文件夹位置
.setOutputDir("E:\\workspace\\springboot\\springboot-mybatisplus\\src\\main\\java")
.setFileOverride(true)
.setServiceName("%sService");
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent("com.zzg.springboot")
.setController("controller")
.setEntity("entity")
).execute();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MybatisPlusGenerator generator = MybatisPlusGenerator.getSingle();
generator.autoGeneration();
}
}
第三步:配置application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.zzg.springboot.entity
第四步:项目的配置信息
package com.zzg.springboot.config;
import javax.sql.DataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
@Configuration
//扫描dao或者是Mapper接口
@MapperScan("com.zzg.springboot.mapper*")
public class MybatisPlusConfig {
/***
* plus 的性能优化
* @return
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/**/
performanceInterceptor.setMaxTime(1000);
/**/
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
/**
* @Description : mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
// 配置数据源
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name="transactionManager")
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
第五步:启动springbootApplication
package com.zzg.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMybatisPlus {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(SpringBootMybatisPlus.class, args);
System.out.println("============= SpringBoot web Start Success =============");
}
}
项目关联的entity层、dao层、service层、controller层和*Mapper.xml文件
package com.zzg.springboot.entity;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import java.io.Serializable;
/**
*
* 学员表
*
*
* @author zzg123
* @since 2018-07-15
*/
public class TStudent implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "sid", type = IdType.AUTO)
private Integer sid;
private String sname;
private String sex;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "TStudent{" +
", sid=" + sid +
", sname=" + sname +
", sex=" + sex +
"}";
}
}
package com.zzg.springboot.mapper;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.zzg.springboot.entity.TStudent;
/**
*
* 学员表 Mapper 接口
*
*
* @author zzg123
* @since 2018-07-15
*/
public interface TStudentMapper extends BaseMapper {
/**
*
* @Title: selectUserByMap
* @Description: 多条件组合查找用户
* @param userId
* @return
* @throws Exception
*/
TStudent selectUserByMap(Map parameterMap) throws Exception;
}
package com.zzg.springboot.service;
import java.util.Map;
import com.baomidou.mybatisplus.service.IService;
import com.zzg.springboot.entity.TStudent;
/**
*
* 学员表 服务类
*
*
* @author zzg123
* @since 2018-07-15
*/
public interface TStudentService extends IService {
/**
*
* @Title: selectUserByMap
* @Description: 多条件组合查找用户
* @param userId
* @return
* @throws Exception
*/
TStudent selectUserByMap(Map parameterMap) throws Exception;
}
package com.zzg.springboot.service.impl;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zzg.springboot.entity.TStudent;
import com.zzg.springboot.mapper.TStudentMapper;
import com.zzg.springboot.service.TStudentService;
/**
*
* 学员表 服务实现类
*
*
* @author zzg123
* @since 2018-07-15
*/
@Service
public class TStudentServiceImpl extends ServiceImpl implements TStudentService {
/**
* 用户数据访问接口
*/
@Resource
private TStudentMapper tstudentMapper;
@Override
public TStudent selectUserByMap(Map parameterMap) throws Exception {
// TODO Auto-generated method stub
return tstudentMapper.selectUserByMap(parameterMap);
}
}
package com.zzg.springboot.controller;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zzg.springboot.entity.TStudent;
import com.zzg.springboot.service.TStudentService;
/**
*
* 学员表 前端控制器
*
*
* @author zzg123
* @since 2018-07-15
*/
@Controller
@RequestMapping("/tStudent")
public class TStudentController {
@Resource
private TStudentService service;
@RequestMapping("/get")
@ResponseBody
public TStudent get(HttpServletRequest request, Model model) throws Exception {
Map map = new HashMap();
map.put("sid", 1);
TStudent student = this.service.selectUserByMap(map);
return student;
}
}
建库脚本:
CREATE TABLE `t_student` (
`sid` INT(11) NOT NULL AUTO_INCREMENT,
`sname` VARCHAR(255) NULL DEFAULT '0',
`sex` CHAR(2) NULL DEFAULT '0',
PRIMARY KEY (`sid`)
)
COMMENT='学员表'
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
MyBatisPlus官网学习地址: http://mp.baomidou.com/#/install