springboot2.x整合Mybatis-Plus3.1

springboot2.x整合Mybatis-Plus3.1

這裏就不講解Mybatis-Plus的優勢了,大家各自在網上也能查詢到
此片文章包含了

  • 代碼自動生成
  • 分頁查詢
  • 字段自動填充
    文章最下方有github地址
    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>org.example</groupId>
    <artifactId>springbootMybatisPlus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </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.1.2</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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.0.7.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件

server:
  port: 8083
spring:
  datasource:
    url: jdbc:mysql://192.168.0.234:3306/ayjshop?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
mybatis-plus:
  global-config:
    db-config:
      id-type: auto
      field-strategy: not_empty
      #駝峯下劃線轉換
      column-underline: true
      #邏輯刪除配置
      logic-delete-value: 0
      logic-not-delete-value: 1
      db-type: mysql
    refresh: false
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

依賴下載完成後,開始準備根據自己數據庫表自動生成代碼
只有加上TODO處的地方,需要手動更改
文件會自動創建到項目內部

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.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

public class MysqlGenerator {

    /**
     * 運行此方法
     */
    public static void main(String[] args) {
        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        // 獲取項目位置
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        // TODO 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.0.234:3306/ayjshop?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // TODO 設置用戶名
        gc.setAuthor("lh");
        gc.setOpen(true);
        // 自定義文件命名,注意 %s 會自動填充表實體屬性!
        gc.setControllerName("%sController");
        // service 命名方式
        gc.setServiceName("%sService");
        // service impl 命名方式
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二級緩存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(false);
        // 設置日期格式爲Date
        gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);



        // TODO 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模塊名"));
        pc.setParent("com.lh.test");
        pc.setEntity("model");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        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.ftl") {
            @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.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        // 設置邏輯刪除鍵
        strategy.setLogicDeleteFieldName("deleted");
        // TODO 指定生成的bean的數據庫表名
        strategy.setInclude("ayj_test");
        //strategy.setSuperEntityColumns("id");
        // 駝峯轉連字符
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        // 選擇 freemarker 引擎需要指定如下加,注意 pom 依賴必須有!
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

Contorller
默認代碼生成的註解只有@Controller,需要手動改成@RestController
如果有朋友知道如何知道如何自定義註解,歡迎留言

import com.lh.service.AyjTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lh
 * @since 2020-04-28
 */
@RestController
@RequestMapping("/ayj-test")
public class AyjTestController {
    @Autowired
    private AyjTestService ayjTestService;

    @PostMapping("/insert")
    public void insert() {
        ayjTestService.insert();
    }

    @PostMapping("/update")
    public void update() {
        ayjTestService.updateById();
    }

    @PostMapping("/selectByCriteria")
    public Object selectByCriteria() {
        return ayjTestService.selectByCriteria();
    }
}

Model
這裏我們在createTime和LastModifyTime兩個字段上加上註解,爲後面的自動填充字段做準備

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.Date;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author lh
 * @since 2020-04-28
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class AyjTest extends Model<AyjTest> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    /**
     * 結合配置,來實現自動填充字段
     */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.UPDATE)
    private Date lastModifyTime;


    @Override
    protected Serializable pkVal() {
        return this.id;
    }

}

Mapper
因爲繼承了BaseMapper的原因,這裏只需要添加一下我們手動寫Sql,此例就不做演示了

import com.lh.model.AyjTest;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author lh
 * @since 2020-04-28
 */
public interface AyjTestMapper extends BaseMapper<AyjTest> {

}

Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lh.mapper.AyjTestMapper">

    <!-- 通用查詢映射結果 -->
    <resultMap id="BaseResultMap" type="com.lh.model.AyjTest">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="create_time" property="createTime" />
        <result column="last_modify_time" property="lastModifyTime" />
    </resultMap>

</mapper>

Service
這裏我們寫三個測試的接口

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lh.model.AyjTest;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服務類
 * </p>
 *
 * @author lh
 * @since 2020-04-28
 */
public interface AyjTestService extends IService<AyjTest> {
    void insert();

    void updateById();

    IPage selectByCriteria();
}

Impl
其實這裏不用我們引入AyjTestMapper
因爲我們的impl實現類默認繼承了ServiceImpl
在ServiceImpl中,已經默認引入了BaseMapper,如果不需要使用我們自定義的sql,我們可以直接使用baseMapper來完成部分的業務邏輯
這裏的insert和update方法,主要是爲了測試自動填充字段的使用

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.model.AyjTest;
import com.lh.mapper.AyjTestMapper;
import com.lh.service.AyjTestService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服務實現類
 * </p>
 *
 * @author lh
 * @since 2020-04-28
 */
@Service
@Transactional
public class AyjTestServiceImpl extends ServiceImpl<AyjTestMapper, AyjTest> implements AyjTestService {

    @Autowired
    private AyjTestMapper ayjTestMapper;

    @Override
    public void insert() {
        AyjTest ayjTest = new AyjTest();
        ayjTest.setName("test");
        ayjTestMapper.insert(ayjTest);
    }

    @Override
    public void updateById() {
        AyjTest ayjTest = new AyjTest();
        ayjTest.setId(1);
        ayjTest.setName("test_update");
        ayjTestMapper.updateById(ayjTest);
    }

    /**
     * 分頁條件查詢
     * @return
     */
    @Override
    public IPage selectByCriteria() {
        // 添加分頁信息,一般是由前端傳入,這裏就直接寫死
        Page<AyjTest> page = new Page<AyjTest>(1, 2);
        // 添加查詢條件
        QueryWrapper<AyjTest> queryWrapper = new QueryWrapper<AyjTest>();
        queryWrapper.eq("name", "test");
        // 調用查詢
        IPage<AyjTest> iPage = ayjTestMapper.selectPage(page, queryWrapper);
        return iPage;
    }
}

代碼編寫後,來對mybatis plus的分頁做一些配置

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Copyright (C), 2006-2010, ChengDu ybya info. Co., Ltd.
 * FileName: MybatisPlusConfig.java
 *
 * @author lh
 * @version 1.0.0
 * @Date 2020/04/24 15:43
 */
@Configuration
public class MybatisPlusConfig {
    private final static Logger logger = LoggerFactory.getLogger(MybatisPlusConfig.class);

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

}

字段自動填充配置
對於要自動填充的字段,必須在實體類的字段上添加@TableField註解

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Copyright (C), 2006-2010, ChengDu ybya info. Co., Ltd.
 * FileName: MyMetaObjectHandler.java
 *
 * @author lh
 * @version 1.0.0
 * @Date 2020/04/24 14:05
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private final static Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

//    @Autowired
//    private CurrentUserUtils currentUserUtils;

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getValue("createTime") == null) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            logger.info("自動填充創建時間");
        }
        if (metaObject.getValue("lastModifyTime") == null) {
            this.setFieldValByName("lastModifyTime", new Date(), metaObject);
            logger.info("自動填充最後修改時間");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
            //這裏使用et.lastModifyTime,是因爲mybatis自動生代碼裏面的updateById方法,添加了@Param("et")註解,如果是直接獲取lastModifyTime會報錯
        if (metaObject.getValue("et.lastModifyTime") == null) {
            this.setFieldValByName("et.lastModifyTime", new Date(), metaObject);
            logger.info("自動填充最後修改時間");
        }
    }

最後直接編寫啓動類
配置中添加對mapper文件的掃描

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.lh.mapper")
public class Application {
    public static void main(String[] args){
            SpringApplication.run(Application.class, args);
        }
}

github地址
若有不足之處,歡迎補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章