版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/struggling_rong/article/details/79789362
Mybatis Plus是一款非常优秀的Mybatis扩展插件,该开源项目是由国人发起的。使用该插件可以简化我们的开发,它有很多优良的特性,比如通用CRUD操作,支持ActiveRecord,内置分页插件等等。
1.添加pom依赖
<!--mybatis plus会维护mybatis依赖,去除该依赖-->
<!--<dependency>-->
<!--<groupId>org.mybatis.spring.boot</groupId>-->
<!--<artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--<version>1.3.0</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
2.配置文件中配置mybatis plus属性
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.my.webapp.dao.entity
#typeEnumsPackage: com.baomidou.springboot.entity.enums
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 1
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 1
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置(下面3个配置)
logic-delete-value: 0
logic-not-delete-value: 1
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
#meta-object-handler: com.baomidou.springboot.xxx
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
3.创建实体类和Mapper
先创建一张测试表
create table t_wa_user
(
id bigint auto_increment
primary key,
user_name varchar(45) not null comment '用户名',
password varchar(45) not null comment '密码'
)
comment '用户表'
;
创建实体类
User.java
package com.my.webapp.dao.entity;
import com.baomidou.mybatisplus.annotations.TableName;
/**
*/
//不指定表名默认为user表
@TableName("t_wa_user")
public class User {
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建Mapper,继承mybatis plus包下的BaseMapper接口
UserMapper.java
package com.my.webapp.dao.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.my.webapp.dao.entity.User;
/**
*/
public interface UserMapper extends BaseMapper<User> {
}
BaseMapper接口中为我们提供了常用的CRUD操作,我们甚至不需要创建xml文件就可以在代码中直接使用
如:
进行分页查询
private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
@Autowired
private UserMapper userMapper;
@Test
public void queryTest() {
User user = new User();
user.setUserName("测试");
user.setPassword("123456");
userMapper.insert(user);
List<User> users = userMapper.selectPage(new Page<User>(1,2), new EntityWrapper<User>().eq("user_name", "测试"));
logger.debug("size: "+users.size());
}
当然较复杂或使用频率高的sql还是推荐写在xml文件中
4.ActiveRecord模式进行CRUD操作
实体类需要继承Model类
User.java
package com.my.webapp.dao.entity;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
/**
*/
@TableName("t_wa_user")
public class User extends Model<User>{
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//指定主键
@Override
protected Serializable pkVal() {
return this.id;
}
}
然后这样:
@Test
public void insertTest() {
User user = new User();
user.setUserName("测试");
user.setPassword("3243");
user.insert();
}
相信您现在应该已经感受到了mybatis plus的魅力了。
5.使用代码生成器
如果我们需要通过mybatis plus生成实体类,Mapper,xml等。则需要使用代码生成器
1>.添加依赖
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.27-incubating</version>
</dependency>
2>.配置生成参数
MpGenerator.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* <p>
* 代码生成器演示
* </p>
*/
public class MpGenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void generate(GeneratorParam param){
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(param.getPath());
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setKotlin(true); //是否生成 kotlin 代码
gc.setAuthor(param.getAuthor());
// 自定义文件命名,注意 %s 会自动填充表实体属性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(param.getUserName());
dsc.setPassword(param.getPassword());
dsc.setUrl(param.getUrl());
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
strategy.setTablePrefix(new String[] { "t_wa_"});// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[] { param.getTableName() }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定义实体父类
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定义实体,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定义 mapper 父类
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
strategy.setDbColumnUnderline(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.my.webapp");
pc.setModuleName("dao");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定义 xxList.jsp 生成
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
focList.add(new FileOutConfig("/template/list.jsp.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return "D://my_" + tableInfo.getEntityName() + ".jsp";
}
});
cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return param.getPath() + tableInfo.getEntityName() +"Mapper" + ".xml";
}
});
cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 关闭默认 xml 生成,调整生成 至 根目录
//TemplateConfig tc = new TemplateConfig();
//tc.setXml(null);
//mpg.setTemplate(tc);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
// mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
// System.err.println(mpg.getCfg().getMap().get("abc"));
}
public static void main(String[] args) {
GeneratorParam param = new GeneratorParam();
param.setUrl("jdbc:mysql://127.0.0.1:3306/web_app?useUnicode=true&characterEncoding=UTF-8&useSSL=false")
.setUserName("root")
.setTableName("t_wa_sign_record")
.setPath("E://java/")
.setPassword("")
.setAuthor("struggling_rong");
generate(param);
}
}
GeneratorParam.java
/**
*/
public class GeneratorParam {
/**
* 存放文件的路径
*/
private String path;
/**
* 表名
*/
private String tableName;
private String userName;
private String password;
private String url;
private String author;
public String getAuthor() {
return author;
}
public GeneratorParam setAuthor(String author) {
this.author = author;
return this;
}
public String getUserName() {
return userName;
}
public GeneratorParam setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public GeneratorParam setPassword(String password) {
this.password = password;
return this;
}
public String getUrl() {
return url;
}
public GeneratorParam setUrl(String url) {
this.url = url;
return this;
}
public String getPath() {
return path;
}
public GeneratorParam setPath(String path) {
this.path = path;
return this;
}
public String getTableName() {
return tableName;
}
public GeneratorParam setTableName(String tableName) {
this.tableName = tableName;
return this;
}
}
执行main方法后,E:\java目录下则生成了我们想要的文件。