一、引入依赖:
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- mybatis-plus自动生成工具 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- Velocity模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
二、CodeGenerator编写
这里设置了只生成entity、mapper接口和mapper.xml文件
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {
private static String tableName = "mvc1";
private static String url = "jdbc:mysql://127.0.0.1:3306/"+tableName+"?useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false&useLegacyDatetimeCode=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
private static String driverClassName = "com.mysql.cj.jdbc.Driver";
private static String username = "root";
private static String password = "";
private static String parentPackage = "com.example.mybatisplus";
//没有模块时为空字符串 ""
private static String modulName = "/mybatis-plus";
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir") + modulName;
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("yangmingqiang");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
// dsc.setSchemaName("public");
dsc.setDriverName(driverClassName);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(modulName);
pc.setParent(parentPackage);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
cfg.setFileCreate((configBuilder, fileType, filePath) -> {
//如果是Entity则直接返回true表示写文件
if (fileType == FileType.ENTITY) {
return true;
}
//否则先判断文件是否存在
File file = new File(filePath);
boolean exist = file.exists();
if (!exist) {
file.getParentFile().mkdirs();
}
//文件不存在或者全局配置的fileOverride为true才写文件
return !exist || configBuilder.getGlobalConfig().isFileOverride();
});
// 如果模板引擎是 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) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.disable(TemplateType.CONTROLLER, TemplateType.SERVICE);
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
三、Wrapper常用方法
函数名 | 说明 | 例子 |
---|---|---|
eq | 等于= | eq("name", "张三") --> name = '张三' |
ne | 不等于<> | ne("name", "张三") --> name <> '张三' |
gt | 大于> | gt("age", 18) --> age > 18 |
ge | 大于等于>= | ge("age", 18) --> age >= 18 |
lt | 小于 | lt("age", 18) --> age < 18 |
le | 小于等于 <= | le("age", 18) --> age <= 18 |
between | between 值1 and 值2 | between("age", 18, 30) --> age between 18 and 30 |
notBetween | not between 值1 and 值2 | notBetween("age", 18, 30) |
like | liek '%值%' | like("name", "王") --> name like '%王%' |
notLike | not like '%值%' | notLike("name", "王") |
likeLeft | like ‘%值’ | |
likeRight | like ‘值%’ | |
isNull | 字段 is null | |
isNotNull | 字段 is not null | |
in | 字段 in () | in("age", {1, 2, 3}) --> age in (1, 2, 3) |
notIn | 字段 not in () | |
groupBy | group by 字段, ... | groupBy("id", "name") --> group by id, name |
orderByDesc | order by 字段, ... desc | |
orderBy | order by 字段, ... | |
last | 拼接sql | last("limit 10 offset 0") --> sql最后加上limit 10 offset 0 |
四、使用例子
@SpringBootTest
class MybatisPlusApplicationTests {
@Resource
private UsersMapper usersMapper;
@Test
void contextLoads() {
LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.eq(Users::getID, 3);
lambdaUpdateWrapper.set(Users::getUsername, "yang");
usersMapper.update(null, lambdaUpdateWrapper); //返回受影响行数
// lambdaUpdateWrapper.clear();
// lambdaUpdateWrapper.eq(Users::getRights, 0);
// Users user = new Users();
// user.setUsername("hahaha");
// usersMapper.update(user, lambdaUpdateWrapper);
LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Users::getRoletype, 0).likeRight(Users::getUsername, "张");
queryWrapper.orderByAsc(Users::getID);
PageModel pageModel = new PageModel(1, 10);
queryWrapper.last(pageModel.toString());
List<Users> list = usersMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
}