Spring Boot 整合 mybatis-plus

簡介

這一篇我們講解如何在springboot下整合mybatis-plus,並訪問數據庫。 MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。 對於 mybatis-plus 的使用,可以參照官網http://mp.baomidou.com/,這裡我就不講解了。

一、創建數據庫表

<code>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;/<code>

二、創建項目

創建一個項目springboot-mybatis

1、pom.xml

<code><project>    <modelversion>4.0.0/<modelversion>    <groupid>com.gf/<groupid>    <artifactid>springboot-mybatis/<artifactid>    <version>0.0.1-SNAPSHOT/<version>    <packaging>jar/<packaging>    <name>springboot-mybatis/<name>    <description>Demo project for Spring Boot/<description>    <parent>        <groupid>org.springframework.boot/<groupid>        <artifactid>spring-boot-starter-parent/<artifactid>        <version>2.1.0.RELEASE/<version>        <relativepath>     /<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>        <dependency>            <groupid>mysql/<groupid>            <artifactid>mysql-connector-java/<artifactid>            <scope>runtime/<scope>        /<dependency>        <dependency>            <groupid>org.projectlombok/<groupid>            <artifactid>lombok/<artifactid>            <optional>true/<optional>        /<dependency>        <dependency>            <groupid>com.baomidou/<groupid>            <artifactid>mybatis-plus-boot-starter/<artifactid>            <version>3.0.1/<version>        /<dependency>        <dependency>            <groupid>org.apache.velocity/<groupid>            <artifactid>velocity/<artifactid>            <version>1.7/<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>/<code>

2. 代碼生成器

AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率。

1. mapper.xml.vm

在resources/templates 下創建 Mapper XML的生成模板

<code><mapper>#if(${enableCache})        <cache>#end#if(${baseResultMap})        <resultmap>#foreach($field in ${table.fields})#if(${field.keyFlag})##生成主鍵排在第一位        #end#end#foreach($field in ${table.commonFields})##生成公共字段    <result>#end#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段        <result>#end#end    /<resultmap>#end#if(${baseColumnList})        #foreach($field in ${table.commonFields})        ${field.name},#end        ${table.fieldNames}    #end/<mapper>/<code>

2. CodeGenerator

<code>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<fileoutconfig> 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();    }}/<fileoutconfig>/<code> 

我運行 CodeGenerator 會發現,我麼需要的 entity、mapper、service、controller 都有了,而且mybatis-plus 為我們封裝了很對常用的方法 ,大大的提到了我們的開發效率

3. application.properties

<code>spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=xxxxxxspring.datasource.password=xxxxxxspring.datasource.driver-class-name=com.mysql.jdbc.Driver/<code>

4. EmployeeController

<code>@RestController@RequestMapping("/employee")public class EmployeeController {    @Autowired    EmployeeService employeeService;    @RequestMapping(value = "/list", method = RequestMethod.GET)    public List<employee> getEmployees() {        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( "[email protected]" );        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( "[email protected]" );        employee.setGender( 2 );        employee.setDId( 2 );        boolean b = employeeService.save( employee );        if(b) {            return "sava success";        }else {            return "sava fail";        }    }}/<employee>/<code>

源碼下載:https://github.com/gf-huanchupk/SpringBootLearning


分享到:


相關文章: