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地址
若有不足之处,欢迎补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值