第六篇|第六篇 : SpringBoot 整合 mybatis-plus
文章首发于微信公众号《程序员果果》这一篇我们讲解如何在springboot下整合mybatis-plus,并访问数据库。
地址:https://mp.weixin.qq.com/s/ITZIPCttey-iYCyhIa8uSw
本篇源码:https://github.com/gf-huanchupk/SpringBootLearning
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
文章图片
对于 mybatis-plus 的使用,可以参照官网http://mp.baomidou.com/,这里我就不讲解了。
一、创建数据库表
DROP TABLE IF EXISTS `tb_employee`;
CREATE TABLE `tb_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
二、创建项目 创建一个项目springboot-mybatis
1、pom.xml
4.0.0 com.gf
springboot-mybatis
0.0.1-SNAPSHOT jarspringboot-mybatis
Demo project for Spring Boot org.springframework.boot
spring-boot-starter-parent
2.1.0.RELEASE
UTF-8UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.0.1
org.apache.velocity
velocity
1.7
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
2. 代码生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
1. mapper.xml.vm 在resources/templates 下创建 Mapper XML的生成模板
#if(${enableCache}) #end
#if(${baseResultMap})
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
#end
#end
#end
#if(${baseColumnList})#foreach($field in ${table.commonFields})
${field.name},
#end
${table.fieldNames}#end
2. CodeGenerator
package com.gf.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
public class CodeGenerator {public static void main(String[] args) throws InterruptedException {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);
// XML 二级缓存
gc.setBaseResultMap(true);
// XML ResultMap
gc.setBaseColumnList(true);
// XML columList
gc.setOpen(false);
gc.setAuthor("gf");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType( DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useSSL=false");
dsc.setUsername("xxxxxx");
dsc.setPassword("xxxxxx");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.gf");
pc.setController( "controller");
pc.setEntity( "entity" );
//pc.setModuleName("test");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//此处可以修改为您的表前缀
strategy.setTablePrefix(new String[] { "tb_"});
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(new String[] { "tb_employee" });
// 排除生成的表
//strategy.setExclude(new String[]{"test"});
strategy.setEntityLombokModel( true );
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
}}
我运行 CodeGenerator 会发现,我么需要的 entity、mapper、service、controller 都有了,而且mybatis-plus 为我们封装了很对常用的方法 ,大大的提到了我们的开发效率
3. application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=xxxxxx
spring.datasource.password=xxxxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
4. EmployeeController
@RestController
@RequestMapping("/employee")
public class EmployeeController {@Autowired
EmployeeService employeeService;
@RequestMapping(valuehttps://www.it610.com/article/= "https://www.it610.com/list", method = RequestMethod.GET)
public List getEmployees() {
return employeeService.list( null );
}@RequestMapping(valuehttps://www.it610.com/article/= "https://www.it610.com/{id}", method = RequestMethod.GET)
public Employee getEmployeeById(@PathVariable("id") int id) {
return employeeService.getById( id );
}@RequestMapping(valuehttps://www.it610.com/article/= "https://www.it610.com/{id}", method = RequestMethod.PUT)
public String updateEmployee(@PathVariable("id") int id, @RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/lastName", required = true) String lastName,
@RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/email", required = true) String email , @RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/gender", required = true) int gender , @RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/dId", required = true) int dId) {
Employee employee = new Employee();
employee.setId( id );
employee.setLastName( "张" );
employee.setEmail( "zhang@163.com" );
employee.setGender( 1 );
employee.setDId( 1 );
boolean b = employeeService.updateById( employee );
if (b) {
return "update success";
} else {
return "update fail";
}}@RequestMapping(valuehttps://www.it610.com/article/= "https://www.it610.com/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable(valuehttps://www.it610.com/article/= "https://www.it610.com/article/id")int id) {
boolean b = employeeService.removeById( id );
if(b) {
return "delete success";
}else {
return "delete fail";
}}@RequestMapping(valuehttps://www.it610.com/article/= "", method = RequestMethod.POST)
public String postEmployee(@RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/lastName", required = true) String lastName,
@RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/email", required = true) String email , @RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/gender", required = true) int gender , @RequestParam(valuehttps://www.it610.com/article/= "https://www.it610.com/article/dId", required = true) int dId) {Employee employee = new Employee();
employee.setLastName( "王" );
employee.setEmail( "wang@163.com" );
employee.setGender( 2 );
employee.setDId( 2 );
boolean b = employeeService.save( employee );
if(b) {
return "sava success";
}else {
return "sava fail";
}}}
【第六篇|第六篇 : SpringBoot 整合 mybatis-plus】源码下载:https://github.com/gf-huanchupk/SpringBootLearning
文章图片
推荐阅读
- 2018年11月19日|2018年11月19日 星期一 亲子日记第144篇
- Activiti(一)SpringBoot2集成Activiti6
- 《魔法科高中的劣等生》第26卷(Invasion篇)发售
- 拍照一年啦,如果你想了解我,那就请先看看这篇文章
- 亲子日记第186篇,2018、7、26、星期四、晴
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 漫画初学者如何学习漫画背景的透视画法(这篇教程请收藏好了!)
- 两短篇
- 第四十三篇接纳孩子的感受