<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.5.7version>
<relativePath/>
parent>
<groupId>com.yf.cngroupId>
<artifactId>spboot-mybatis-plusartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spboot-mybatis-plusname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.1.1version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.28version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.31version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>1.2.12version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
#端口号
server.port=8081
#数据库相关配置
spring.jackson.time-zone=GMT+8
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
#mybatis.mapper-locations=classpath:mapper/*.xml
# mybatis-plus 配置
mybatis-plus.mapper-locations=classpath:mappers/*.xml
mybatis-plus.configuration.map-underscore-to-camel-case=true
#设置控制台输出sql
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.configuration.cache-enabled=false
mybatis-plus.configuration.call-setters-on-nulls=true
#配置包别名,不同包之间用逗号隔开
mybatis-plus.type-aliases-package=com.yf.cn.spbootmybatisplus.pojo
mybatis-plus.global-config.id-type=0
mybatis-plus.global-config.field-strategy=2
mybatis-plus.global-config.db-column-underline=false
mybatis-plus.global-config.refresh-mapper=true
package com.yf.cn.spbootmybatisplus.utils;
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.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
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 MpGenerator {
public static void main(String[] args) throws InterruptedException {
//用来获取Mybatis-Plus.properties文件的配置信息
//final ResourceBundle rb = ResourceBundle.getBundle("mybatisplus");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("D:/eclipse-mars/mybatissql/src/main/java"); //修改成自己的项目路径一直到java
gc.setFileOverride(true);//覆盖已有文件
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
gc.setAuthor("yf");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper.xml");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setTypeConvert(new MySqlTypeConvertCustom());
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.yf.cn");
//pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("model");
pc.setMapper("dao");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板 引擎是 velocity
//String templatePath = "/templates/mapper.xml.vm";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return "D:/eclipse-mars/mybatissql/src/main/resources" + "/mapper/" + tableInfo.getEntityName() + 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.setExclude(new String[]{rb.getString("tableName")});
//建立包含哪些表空 为所有表
strategy.setInclude();
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
/**
* 自定义类型转换
*/
class MySqlTypeConvertCustom extends MySqlTypeConvert implements ITypeConvert{
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
String t = fieldType.toLowerCase();
if (t.contains("tinyint(1)")) {
return DbColumnType.INTEGER;
}
return super.processTypeConvert(globalConfig, fieldType);
}
}
执行上面工具类的main方法,查看对应的目录,看看是否已经生成可对应的dao、service、controller以及mapper.xml,如果有说明代码生成工具已经成功
将生成的代码复制到实际项目对应的位置,编写测试类进行测试:StudentMapperTest
package com.yf.cn.spbootmybatisplus.mapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yf.cn.spbootmybatisplus.pojo.TestStudent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentMapperTest {
@Autowired
private TestStudentMapper testStudentMapper;
@Test
public void testSaveStudent(){
TestStudent testStudent = new TestStudent();
testStudent.setSage(21);
testStudent.setSname("晓峰");
testStudent.setSsex("男");
testStudent.setFlag("1");
testStudentMapper.insert(testStudent);
}
@Test
public void testSelectPage(){
LambdaQueryWrapper<TestStudent> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.like(TestStudent::getSname,"峰");
lambdaQueryWrapper.orderByDesc(TestStudent::getId).orderByAsc(TestStudent::getSname);
Page<TestStudent> studentPage = new Page<TestStudent>(1 , 2);
IPage<TestStudent> studentIPage = testStudentMapper.selectPage(studentPage, lambdaQueryWrapper);
System.out.println("总页数: "+studentIPage.getPages());
System.out.println("总记录数: "+studentIPage.getTotal());
System.out.println("当前页: "+studentIPage.getCurrent());
System.out.println("每页条数限制: "+studentIPage.getSize());
studentIPage.getRecords().forEach(System.out::println);
}
}
10. 执行查询方法:testSelectPage,方法执行成功,控制台输出如下:至此springboot+mybatis-plus分页、排序以及条件查询完成