SpringBoot与MybatisPlus1-搭建mybatisplus
在很久之前我们操作数据库采用的是原始的JDBC来对数据进行CRUD,比较繁琐,需要进行很多重复性的工作。就算进行单表操作也要写很多的sql,十分的不便,后来就有人实现了一个ORM框架,hibernate就问世了。hibernate通过简单xml配置,不需要写sql就可以进行查询操作,但是hibernate封装的太死,不够灵活,不能进行sql优化,不适合复杂的查询操作。后来就出现了mybatis,mybatis是半自动化的ORM框架,可以简化我们对数据库的操作,并且可以自己控制sql语句,进行sql优化,不管多复杂的查询都能利用sql实现。mybatis搭配通用mapper可以实现单表的CRUD操作,在搭配一个代码生成插件,可以通过数据库表生成我们需要的mapper,mapper.xml,service代码,对单表操作我们不需要写sql了,也可以使用java实现简单的查询。
MybatisPlus是mybatis的扩展,对mybatis做了增强,有代码生成,单表查询,和简单查询的功能以及分页插件,详细的可以参考官网:mybatisplus
本文将实现springboot与mybatisplus3的整合,并实现简单的功能测试。 涉及的相关技术:
mybatis,mybatisplus,mysql,druid
一,mybatisplus与springboot的搭建
1,创建一个springboot项目
pom.xml的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jack</groupId>
<artifactId>mybatisplus_study1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisplus_study1</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0-gamma</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2,创建一张测试的表,创建语句如下:
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(12) DEFAULT NULL COMMENT '姓名',
`sex` tinyint(255) DEFAULT NULL COMMENT '性别,女为0,男为1',
`note` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
3,编写代码生成相关的代码
代码生成:
package com.jack.mybatisplus_study1.util;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.sql.Driver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* create by jack 2018/8/4
*
* @auther jack
* @date: 2018/8/4 11:32
* @Description:
*/
public class MpGeneratorUtil {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("F:\\mystudy\\mybatisplus_study\\test1");
gc.setFileOverride(true);
gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
// .setKotlin(true) 是否生成 kotlin 代码
gc.setAuthor("jack");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
/*dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});*/
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8");
mpg.setDataSource(dsc);
Driver driver;
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
// 此处可以修改为您的表前缀
//strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(new String[] { "student" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定义实体父类
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定义实体,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定义 mapper 父类
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.jack.mybatisplus_study1");
//pc.setModuleName("test");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定义 xxList.jsp 生成
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
/*focList.add(new FileOutConfig("/template/list.jsp.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return "D://my_" + tableInfo.getEntityName() + ".jsp";
}
});*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return "F:\\mystudy\\mybatisplus_study\\test1\\mapper\\" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 关闭默认 xml 生成,调整生成 至 根目录
TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
mpg.setTemplate(tc);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
// mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
4,把生成的代码拷贝到相应的目录
拷贝的目录如下图:
5,配置application.yml文件
配置如下:
server:
port: 9090
spring:
application:
name: mybatisplus
datasource:
name: test
url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=true
username: root
password: root
#使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis-plus:
# 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*.xml
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.jack.mybatisplus_study1.entity
global-config:
# 数据库相关配置
db-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 3
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#mp2.3+ 全局表前缀 mp_
#table-prefix: mp_
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
# Sequence序列接口实现类配置
#key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
#逻辑删除配置(下面3个配置)
logic-delete-value: 1
logic-not-delete-value: 0
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
configuration:
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull, oracle数据库必须配置
jdbc-type-for-null: 'null'
#开启mybatis的sql日志
logging:
level:
com.jack.mybatisplus_study1: debug
6,进行相关的java配置
1)数据源的配置:
package com.jack.mybatisplus_study1.config;
import com.alibaba.druid.pool.DruidDataSource;
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 javax.sql.DataSource;
/**
* create by jack 2018/8/4
*
* @auther jack
* @date: 2018/8/4 10:04
* @Description:
*/
@Configuration
public class DatabaseConfig {
/**
* 注入环境变量的值
*/
@Autowired
private Environment environment;
/**
* 获取数据源DataSource
* @return
*/
@Bean
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
druidDataSource.setUsername(environment.getProperty("spring.datasource.username"));
druidDataSource.setPassword(environment.getProperty("spring.datasource.password"));
druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
druidDataSource.setMaxActive(Integer.parseInt(environment.getProperty("spring.datasource.maxActive")));
druidDataSource.setInitialSize(Integer.parseInt(environment.getProperty("spring.datasource.initialSize")));
druidDataSource.setMaxWait(Long.parseLong(environment.getProperty("spring.datasource.maxWait")));
druidDataSource.setMinIdle(Integer.parseInt(environment.getProperty("spring.datasource.minIdle")));
druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(environment.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")));
druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(environment.getProperty("spring.datasource.minEvictableIdleTimeMillis")));
druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
druidDataSource.setTestWhileIdle(Boolean.parseBoolean(environment.getProperty("spring.datasource.testWhileIdle")));
druidDataSource.setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnBorrow")));
druidDataSource.setTestOnReturn(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnReturn")));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(environment.getProperty("spring.datasource.poolPreparedStatements")));
druidDataSource.setMaxOpenPreparedStatements(Integer.parseInt(environment.getProperty("spring.datasource.maxOpenPreparedStatements")));
return druidDataSource;
}
}
2)mybatisplus的相关配置
package com.jack.mybatisplus_study1.config;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import javax.sql.DataSource;
/**
* create by jack 2018/8/4
*
* @auther jack
* @date: 2018/8/4 09:17
* @Description:
*/
@Configuration
//@MapperScan("com.jack.mybatisplus_study1.mapper*")
public class MybatisPlusConfig {
/*@Bean("mybatisSqlSession")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourceLoader resourceLoader) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
sqlSessionFactory.setTypeAliasesPackage("com.jack.mybatisplus_study1.entity");
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[]{
new PaginationInterceptor(),
new PerformanceInterceptor(),
new OptimisticLockerInterceptor()
});
//sqlSessionFactory.setGlobalConfig(globalConfiguration);
//sqlSessionFactory.setGlobalConfig();
//GlobalConfiguration globalConfiguration =
return sqlSessionFactory.getObject();
}*/
/**
* 相当于顶部的:
* {@code @MapperScan("com.baomidou.springboot.mapper*")}
* 这里可以扩展,比如使用配置文件来配置扫描Mapper的路径
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.jack.mybatisplus_study1.mapper*");
return scannerConfigurer;
}
/**
* 分页插件,自动识别数据库类型
* 多租户,请参考官网【插件扩展】
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/*@Bean
public GlobalConfig globalConfiguration() {
GlobalConfig conf = new GlobalConfig();
return conf;
}*/
}
7,编写测试的controller
package com.jack.mybatisplus_study1.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.jack.mybatisplus_study1.entity.Student;
import com.jack.mybatisplus_study1.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.sql.Wrapper;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author jack
* @since 2018-08-04
*/
@RestController
@RequestMapping("/student")
public class StudentController extends ApiController{
@Autowired
private IStudentService studentService;
/**
* 添加学生
* @param student
* @return
*/
@PostMapping
public boolean addStudent(@RequestBody Student student){
/*JSONObject rs = new JSONObject();
rs.put("result",studentService.insert(student));*/
return studentService.insert(student);
}
/**
* 删除学生
* @param id
* @return
*/
@DeleteMapping("/{id}")
public boolean deleteStudent(@PathVariable("id") Integer id){
boolean rs = studentService.deleteById(id);
return rs;
}
/**
* 修改学生
* @param student
* @return
*/
@PutMapping
public boolean updateStudent(@RequestBody Student student){
boolean rs = studentService.updateById(student);
return rs;
}
/**
* 查找所有学生
* @return
*/
@GetMapping
public List<Student> getAllStudent(){
return studentService.selectList(null);
}
/**
* 通过指定id查找学生
* @param id
* @return
*/
@GetMapping("/{id}")
public Student getStudentById(@PathVariable("id") Integer id){
return studentService.selectById(id);
}
/**
* 通过指定条件查询学生
* @param name
* @return
*/
@GetMapping("/name/{name}")
public List<Student> getSudentByName(@PathVariable("name") String name){
QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>();
queryWrapper.eq("name",name);
List<Student> rs = studentService.selectList(queryWrapper);
return rs;
}
}
这就是主要的代码了,根据详细的代码,后面会放github的地址,查看源码
二,测试mybatisplus的操作
1,新增
2,删除
3,修改
4,查找所有学生数据:
5,查找指定id的学生数据
6,测试java构建查询条件
详细的项目,请参考源码:
群号在左边,欢迎各位加群进行技术交流,
推荐阅读