文章首发于微信公众号《程序员果果》 地址:
简介
这一篇我们讲解如何在springboot下整合mybatis-plus,并访问数据库。 MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
对于 mybatis-plus 的使用,可以参照官网,这里我就不讲解了。
一、创建数据库表
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 jar springboot-mybatis Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.1.0.RELEASE UTF-8 UTF-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#if(${baseColumnList})#end#end#foreach($field in ${table.commonFields})##生成公共字段 #end#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段 #end#end #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 } }; ListfocList = 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/testspring.datasource.username=xxxxxxspring.datasource.password=xxxxxxspring.datasource.driver-class-name=com.mysql.jdbc.Driver
###4. EmployeeController
@RestController@RequestMapping("/employee")public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping(value = "/list", method = RequestMethod.GET) public ListgetEmployees() { return employeeService.list( null ); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Employee getEmployeeById(@PathVariable("id") int id) { return employeeService.getById( id ); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String updateEmployee(@PathVariable("id") int id, @RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "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(value = "/{id}", method = RequestMethod.DELETE) public String delete(@PathVariable(value = "id")int id) { boolean b = employeeService.removeById( id ); if(b) { return "delete success"; }else { return "delete fail"; } } @RequestMapping(value = "", method = RequestMethod.POST) public String postEmployee(@RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "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"; } }}
源码
关注我
欢迎扫码或微信搜索公众号《程序员果果》关注我,关注有惊喜~