MybatisPlus
为什么我要学习,因为我去一家公司实习,代码硬是看不懂,最后请教了别人才知道全是mybatisplus的代码,就没有sql了,所以我们也该跟上步伐,由于新版和旧版可能有一些不一样,所以如果实现不出来效果建议去看官方文档
介绍
国产的开源框架,基于 MyBatis
核⼼功能就是简化 MyBatis 的开发,提⾼效率
所有的CRUD代码它都可以自动化完成
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
- 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击
快速入门
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
注意引入了mybatisplus就不要再引入mybatis的启动器了
application.yml配置
需要注意自己的数据库名字和密码。和配置日志
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
创建实体类
这里使用了lombok插件
package com.example.mybatisplus.entity;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
创建 Mapper接口
继承BaseMapper并加上实体类的泛型
package com.example.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
启动类需要添加@MapperScan(“mapper所在的包”),扫描 Mapper 文件夹,否则无法加载对应的Mapper bean
package com.example.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
测试
package com.example.mybatisplus.mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserMapperTest {
@Autowired
private UserMapper mapper;
@Test
void test(){
mapper.selectList(null).forEach(System.out::println);
//UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper,所以不填写就是无任何条件
}
}
service接口
public interface UserService extends IService<User> {
}
service实现类
/**
* service实现类 继承mybatisplus提供通用的service基类
* ServiceImpl<UserMapper, User>
* 2个泛型 :
* 第一个是Mapper接口
* 第二个是对应实体类
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {
}
注意好像只能注入实现类才能使用,注入接口无法使用
常用注解
@TableName
映射数据库的表名,数据库表名为user
描述:用来将实体对象与数据库表名完成映射
修饰范围:作用在类上
常见属性:
value:string类型,指定映射的表名
resultMap:string类型,用来指定XML配置中resultMap的id值
package com.example.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName(value = "user")
public class User1 {
private Integer id;
private String name;
private Integer age;
}
@TableId
数据库插入的id值默认为:全局的唯一id
描述:主键主键
修饰范围:用在属性上
常见属性:
value:String类型,指定实体类中与表对应的主键列名
type:枚举类型,指定主键生成策略
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
value | String | 否 | “” | 主键字段名 |
type | Enum | 否 | IdType.NONE | 主键类型 |
设置主键映射,value 属性映射主键字段名
type 属性设置主键类型,主键的⽣成策略
//数据库ID自增
AUTO(0),
NONE(1),
//用户输入ID
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
//后面3个被淘汰了
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
值 | 描述 |
---|---|
AUTO | 数据库ID自增 |
NONE | mybatisplus set 主键,雪花算法实现 |
INPUT | insert前自行set主键值,手动赋值 |
ASSIGN_ID | mybatisplus分配id,可以使用long,integer,string 类型 |
ASSIGN_UUID | 分配 UUID,必须是String |
INPUT 如果开发者没有⼿动赋值,则数据库通过⾃增的⽅式给主键赋值,如果开发者
⼿动赋值,则存⼊该值。
AUTO 默认就是数据库⾃增,开发者⽆需赋值,会主动回填。但是数据库的主键要有自增长
ASSIGN_ID mybatisplus ⾃动赋值,雪花算法
ASSIGN_UUID 主键的数据类型必须是 String,⾃动⽣成 UUID 进⾏赋值
全局ID生成策略
在全局配置文件中,就不需要在每个pojo的主键上配置了
mybatis-plus:
global-config:
db-config:
id-type: auto
@TableField
描述字段注解(非主键)
修饰范围:用在属性上
默认情况下MP会根据实体类的属性名去映射表的列名。
如果数据库的列表和实体类的属性名不一致了我们可以使用@TableField
注解的value
属性去设置映射关系。
例如:
如果表中一个列名叫 address而 实体类中的属性名为addressStr则可以使用如下方式进行配置。
@TableField("address")
private String addressStr;
映射⾮主键字段,value 映射字段名
exist 表示是否为数据库字段,默认为true, 如果实体类中的成员变量在数据库中没有对应的字段,设置为false,则可以使⽤ exist,VO、DTO
select 表示是否查询该字段
fill 表示是否⾃动填充,将对象存⼊数据库的时候,由MyBatis Plus ⾃动给某些字
段赋值,create_time、update_time
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
value | String | 否 | “” | 数据库字段名 |
exist | boolean | 否 | true | 是否为数据库表字段 |
select | boolean | 否 | true | 进行查询时,是否查询该字段 |
fill | Enum | 否 | FieldFill.DEFAULT | 字段自动填充策略 |
el | String | 否 | “” | 映射为原生 #{ … } 逻辑,相当于写在 xml 里的 #{ … } 部分 |
condition | String | 否 | “” | 字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s} |
update | String | 否 | “” | 字段 update set 部分注入, 例如:update="%s+1":表示更新时会set version=version+1(该属性优先级高于 el 属性) |
numericScale | String | 否 | “” | 指定小数点后保留的位数 |
fill
值 | 描述 |
---|---|
DEFAULT | 默认不处理 |
INSERT | 插入时填充字段 |
UPDATE | 更新时填充字段 |
INSERT_UPDATE | 插入和更新时填充字段 |
1.给表添加 create_time、update_time 字段
2、实体类中添加成员变量
因为第一次添加时修改时间也要添加,所以updateTime应该有两个,INSERT_UPDATE
package com.example.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type =IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
3、创建自动填充处理器
注意别忘记了注入IOC容器里面
注意createTime和updateTime是实体类的属性名,不是数据库的字段名,和wrapper的条件区分一下
package com.example.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
新版
package com.blb.mybatisplus2.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject,"createTime",Date.class,new Date());
this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
}
}
@Version
标记乐观锁,通过 version 字段来保证数据的安全性,当修改数据的时候,会以 version 作为条件,当条件成立的时候才会修改成功
例如:
version = 2
线程 1:update … set version = 2 where version = 1
线程2 :update … set version = 2 where version = 1
这样就只有一个线程会执行
乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
1、数据库表添加 version 字段,默认值为 1
2、实体类添加 version 成员变量,并且添加 @Version
package com.example.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type =IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private int version;
}
3、注册配置类
新版
package com.blb.mybatisplus2.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
老版
@Configuration
public class MybatisPlusConfig {
/**
* 乐观锁插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
如果修改发现version没有改变,那么应该先通过id查询出来,再进行修改
@EnumValue
1、通用枚举类注解,将数据库字段映射成实体类的枚举类型成员变量
package com.example.mybatisplus.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
public enum StatusEnum {
WORK(1,"上班"),
REST(0,"休息");
@EnumValue
private Integer code;
private String msg;
StatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type =IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Integer version;
private StatusEnum status;
}
application.yml
注意是:type-enums-package而不是type-aliases-package
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-enums-package: com.example.mybatisplus.enums
方式二:实现接口
package com.example.mybatisplus.enums;
import com.baomidou.mybatisplus.annotation.IEnum;
public enum AgeEnum implements IEnum<Integer> {
young(18,"18"),
old(20,"20")
;
private Integer code;
private String msg;
AgeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public Integer getValue() {
return this.code;
}
}
逻辑删除 @TableLogic
映射逻辑删除
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
value | String | 否 | “” | 逻辑未删除值 |
delval | String | 否 | “” | 逻辑删除值 |
物理删除
在删除的时候直接将数据库的数据从数据库删除掉
逻辑删除
在逻辑层面控制删除,通常会在表里加入对应的逻辑删除标识字段,deleted,默认是有效的值为0,当用户删除时将数据修改为1.查询是只查询deleted=0的
1、数据表添加 deleted 字段
2、实体类添加注解
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type =IdType.AUTO)
private Long id;
private String name;
private AgeEnum age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Integer version;
private StatusEnum status;
@TableLogic
private Integer deleted;
}
3、application.yml 添加配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-enums-package: com.example.mybatisplus.enums
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1
执行删除操作其实执行的是更新操作,把deleted从0改成1,并且也查询不会查询deleted为1的数据
@OrderBy
描述:内置 SQL 默认指定排序,优先级低于 wrapper 条件查询
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
isDesc | boolean | 否 | true | 是否倒序查询 |
delval | String | 否 | Short.MAX_VALUE | 数字越小越靠前 |
配置
全局ID生成策略
在全局配置文件中,就不需要在每个pojo的主键上配置了
mybatis-plus:
global-config:
db-config:
id-type: auto
全局设置表名前缀
一般一个项目表名的前缀都是统一风格的,这个时候如果一个个设置就太麻烦了。我们可以通过配置来设置全局的表名前缀。
例如:
如果一个项目中所有的表名相比于类名都是多了个前缀: tb_
。这可以使用如下方式配置
mybatis-plus:
global-config:
db-config:
#表名前缀
table-prefix: tb_
关闭自动解析驼峰写法
mybatis-plus会自动将驼峰写法解析成带下划线的字段
如果需要关闭我们可以使用如下配置进行关闭。
mybatis-plus:
configuration:
# 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射
map-underscore-to-camel-case: false
日志
如果需要打印MP操作对应的SQL语句等,可以配置日志输出。
配置方式如下:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
条件构造器wrapper
Wrapper : 条件构造抽象类,最顶端父类
AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
QueryWrapper : Entity 对象封装操作类,不是用lambda语法
UpdateWrapper : Update 条件封装,用于Entity对象更新操作
AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column。
LambdaQueryWrapper :看名称也能明白就是用于Lambda语法使用的查询Wrapper
LambdaUpdateWrapper : Lambda 更新封装Wrapper
方法
注意:以下条件构造器的方法入参中的 column 均表示数据库字段
函数名 | 说明 | 例子 |
---|---|---|
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)—>age not between 18 and 30 |
like | LIKE ‘%值%’ | like(“name”, “王”)—>name like ‘%王%’ |
notLike | NOT LIKE ‘%值%’ | notLike(“name”, “王”)—>name not like ‘%王%’ |
likeLeft | LIKE ‘%值’ | likeLeft(“name”, “王”)—>name like ‘%王’ |
likeRight | LIKE ‘值%’ | likeRight(“name”, “王”)—>name like ‘王%’ |
isNul | 字段 IS NULL | isNull(“name”)—>name is null |
isNotNull | 字段 IS NOT NULL | isNotNull(“name”)—>name is not null |
in | 字段 IN (value.get(0), value.get(1), …) | in(“age”,{1,2,3})—>age in (1,2,3) |
in | 字段 IN (v0, v1, …) | in(“age”, 1, 2, 3)—>age in (1,2,3) |
notIn | 字段 NOT IN (value.get(0), value.get(1), …) | notIn(“age”,{1,2,3})—>age not in (1,2,3) |
notIn | 字段 NOT IN (v0, v1, …) | age not in (1,2,3) |
inSql | 字段 IN ( sql语句 ) | inSql( " age ", “1 ,2,3,4,5,6”)—>age in (1,2,3,4,5,6) , inSql(“id”, “select id from table where id < 3”)—>id in (select id from table where id |
notInSql | 字段 NOT IN ( sql语句 ) | notInSql(“age”, “1,2,3,4,5,6”)—>age not in (1,2,3,4,5,6),notInSql(“id”, “select id from table where id < 3”)—>id not in (select id from table where id < 3) |
groupBy | 分组:GROUP BY 字段, … | groupBy(“id”, “name”)—>group by id,name |
orderByAsc | 排序:ORDER BY 字段, … ASC | orderByAsc(“id”, “name”)—>order by id ASC,name ASC |
orderByDesc | 排序:ORDER BY 字段, … DESC | orderByDesc(“id”, “name”)—>order by id DESC,name DESC |
orderBy | 排序:ORDER BY 字段, … | orderBy(true, true, “id”, “name”)—>order by id ASC,name ASC |
having | HAVING ( sql语句 ) | having(“sum(age) > 10”)—>having sum(age) > 10 |
or | 拼接 OR 注意事项:主动调用or表示紧接着下一个方法不是用and连接!(不调用or则默认为使用and连接) | eq(“id”,1).or().eq(“name”,“老王”)—>id = 1 or name = ‘老王’ |
OR 嵌套 | or(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))—>or (name = ‘李白’ and status <> ‘活着’) | |
and | AND 嵌套 | and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))—>and (name = ‘李白’ and status <> ‘活着’) |
nested | 正常嵌套 不带 AND 或者 OR | nested(i -> i.eq(“name”, “李白”).ne(“status”, “活着”))—>(name = ‘李白’ and status <> ‘活着’) |
last | 无视优化规则直接拼接到 sql 的最后 注意事项: 只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用 | last(“limit 1”) |
exists | 拼接 EXISTS ( sql语句 ) | exists(“select id from table where age = 1”)—>exists (select id from table where age = 1) |
notExists | 拼接 NOT EXISTS ( sql语句 ) | notExists(“select id from table where age = 1”)—>not exists (select id from table where age = 1) |
QueryWrapper
select
设置查询字段
select(String... sqlSelect)
select(Predicate<TableFieldInfo> predicate)
select(Class<T> entityClass, Predicate<TableFieldInfo> predicate)
select(String… sqlSelect) 方法的测试为要查询的列名
SQL语句如下:
SELECT
id,user_name
FROM
USER
MP写法如下:
@Test
public void testSelect01(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id","user_name");
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
例: select(“id”, “name”, “age”)
例: select(i -> i.getProperty().startsWith(“test”))
select(Class entityClass, Predicate predicate)
方法的第一个参数为实体类的字节码对象,第二个参数为Predicate类型,可以使用lambda的写法,过滤要查询的字段 (主键除外) 。
SQL语句如下:
SELECT
id,user_name
FROM
USER
MP写法如下:
@Test
public void testSelect02(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select(User.class, new Predicate<TableFieldInfo>() {
@Override
public boolean test(TableFieldInfo tableFieldInfo) {
return "user_name".equals(tableFieldInfo.getColumn());
}
});
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
方法第一个参数为Predicate类型,可以使用lambda的写法,过滤要查询的字段 (主键除外) 。
SQL语句如下:
SELECT
id,user_name,PASSWORD,NAME,age
FROM
USER
就是不想查询address这列,其他列都查询了
MP写法如下:
@Test
public void testSelect03(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>(new User());
queryWrapper.select(new Predicate<TableFieldInfo>() {
@Override
public boolean test(TableFieldInfo tableFieldInfo) {
return !"address".equals(tableFieldInfo.getColumn());
}
});
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
UpdateWrapper
可以使用UpdateWrapper的set方法来设置要更新的列及其值。同时这种方式也可以使用Wrapper去指定更复杂的更新条件。
set
set(String column, Object val)
set(boolean condition, String column, Object val)
SQL SET 字段
例: set(“name”, “老李头”)
例: set(“name”, “”)—>数据库字段值变为空字符串
例: set(“name”, null)—>数据库字段值变为null
setSql
SQL语句如下:
UPDATE
USER
SET
age = 99
where
id > 1
我们想把id大于1的用户的年龄修改为99,则可以使用如下写法:
@Test
public void testUpdateWrapper(){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.gt("id",1);
updateWrapper.set("age",99);
userMapper.update(null,updateWrapper);
}
设置 SET 部分 SQL
例: setSql("name = '老李头'")
查询Select
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
类型 | 参数名 | 描述 |
---|---|---|
Serializable | id | 主键ID |
Wrapper | queryWrapper | 实体对象封装操作类(可以为 null) |
Collection<? extends Serializable> | idList | 主键ID列表(不能为 null 以及 empty) |
Map<String, Object> | columnMap | 表字段 map 对象 |
IPage | page | 分页查询条件(可以为 RowBounds.DEFAULT) |
查询所有不加条件
//不加任何条件全部查询
List<User> users = mapper.selectList(null);
users.forEach(System.out::println);
查询单条记录
注意:seletOne返回的是一条实体记录,当出现多条时会报错
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
System.out.println(mapper.selectOne(wrapper));
通过id查询
//查询单个id
User user = mapper.selectById(1);
//批量操作查询多个id
List<User> users = mapper.selectBatchIds(Arrays.asList(7, 8, 9));
通过map查询
map只能做等值判断,逻辑判断需要使用wrapper
//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
Map<String,Object> map = new HashMap<>();
map.put("id",7);
mapper.selectByMap(map).forEach(System.out::println);
注意:map中的key对应的是数据库中的列名。例如数据库user_id,实体类是userId,这时map的key需要填写user_id
单条件查询
//查询name为cb的用户
QueryWrapper wrapper=new QueryWrapper();
wrapper.eq("name","cb");
System.out.println(mapper.selectList(wrapper));
多条件查询
//多条件查询
// 查询name为cb,age为18的用户
QueryWrapper wrapper=new QueryWrapper();
Map<String,Object> map=new HashMap<>();
map.put("name","cb");
map.put("age",18);
wrapper.allEq(map);
System.out.println(mapper.selectList(wrapper));
wrapper.gt("age",18); //大于
wrapper.ne("name","cb"); //等于
wrapper.ge("age",18); //大于等于
wrapper.lt("age",18); //小于
wrapper.le("age",18); //小于等于
模糊查询
//模糊查询
QueryWrapper wrapper=new QueryWrapper();
//相对于 like '%b%'
wrapper.like("name","b");
//相当于 like '%b'
wrapper.likeLeft("name","b");
//相当于 like 'b%'
wrapper.likeRight("name","b");
System.out.println(mapper.selectList(wrapper));
子查询
wrapper.inSql("id","select id from user where id < 10");
wrapper.inSql("age","select age from user where age > 3");
排序
wrapper.orderByDesc("age");
wrapper.orderByAsc("age");
wrapper.having("id > 8");
查询数量
返回的是有几条数据
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
System.out.println(mapper.selectCount(wrapper));
将查询结果封装到map
返回map而不是原来的对象
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
mapper.selectMaps(wrapper).forEach(System.out::println);
分页查询
配置
新版
@Configuration
public class MyBatisPlusConfig {
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
老版
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
mapper方法返回page对象
//分页查询
// 第一个参数是页数
// 第二个参数每页的条数
Page<User> page=new Page<>(1,5);
Page<User> result = mapper.selectPage(page, null);
//每页条数
System.out.println(result.getSize());
//总数
System.out.println(result.getTotal());
//查询结果
result.getRecords().forEach(System.out::println);
getCurrent 当前页
getRecords 每页数据list集合
getSize 每页显示记录数
getTotal 总记录数
getPages 总页数
hasNext 是否有下一页
hasPrevious 是否有上一页
mapper方法返回map集合
Page<Map<String,Object>> page = new Page<>(1,2);
mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);
service方法返回page对象
IPage<User> ipage=new Page<>(1,2);
IPage<User> page = userService.page(ipage);
List<User> records = page.getRecords();
System.out.println(records);
//总共数据的条数
System.out.println(page.getTotal());
//总共数据的页数
System.out.println(page.getPages());
xml自定义分页
UserMapper
@Repository
public interface UserMapper extends BaseMapper<User> {
/**
* <p>
* 查询 : 根据年龄查询用户列表,分页显示
* </p>
*
* @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
* @param age 年龄
* @return 分页对象
*/
IPage<User> getByAge(IPage iPage,Integer age);
}
UserMapper.xml 等同于编写一个普通 list 查询,mybatis-plus 自动替你分页
<?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.blb.mybatisplus2.mapper.UserMapper">
<select id="getByAge" resultType="User">
select * from user1 where age=#{age}
</select>
</mapper>
UserServiceImpl.java 调用分页方法
@Test
void xmlPage(){
IPage<User> byAge = userMapper.getByAge(new Page(1, 2), 18);
List<User> records = byAge.getRecords();
System.out.println(records);
}
自定义sql(多表关联)
多表数据库
create table product(
category int ,
count int ,
description varchar(20),
userid bigint(100)
)charset =utf8
ProductVO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductVO {
private Integer category;
private Integer count;
private String description;
private Integer userId;
private String userName;
}
mapper接口
@Repository
public interface UserMapper extends BaseMapper<User> {
@Select("select p.*,u.name username from product p,user u where u.id=p.userid and u.id=#{id}")
List<ProductVO> productList(@Param("id") Integer id);
}
Mapper CRUD 接口
添加Insert
// 插入一条记录
int insert(T entity);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 |
User user = new User();
user.setTitle("dyk");
user.setAge(22);
mapper.insert(user);
System.out.println(user);
MybatisPlus执行BaseMapper的insert方法一次数据库总是出现出现两条一模一样的记录解决办法
每次插入一个数据,数据库总是出现两条一样的数据
解决办法
就是将Delegate IDE build/run actions to Maven (翻译意思是:将IDE构建/运行操作委托给maven)前面的勾勾取消。
idea maven的问题删掉后添加就只有一条数据了
删除Delete
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
类型 | 参数名 | 描述 |
---|---|---|
Wrapper | wrapper | 实体对象封装操作类(可以为 null) |
Collection<? extends Serializable> | idList | 主键ID列表(不能为 null 以及 empty) |
Serializable | id | 主键ID |
Map<String, Object> | columnMap | 表字段 map 对象 |
通过id删除
mapper.deleteById(1);
批量删除
mapper.deleteBatchIds(Arrays.asList(7,8));
通过条件删除
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",14);
mapper.delete(wrapper);
通过map删除
Map<String,Object> map = new HashMap<>();
map.put("id",10);
mapper.deleteByMap(map);
修改Update
// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 (set 条件值,可为 null) |
Wrapper | updateWrapper | 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) |
先查id在修改
User user = mapper.selectById(7);
mapper.updateById(user);
根据条件修改
User user = mapper.selectById(1);
user.setTitle("小红");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",22);
mapper.update(user,wrapper);
Service CRUD 接口
Save
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 |
Collection | entityList | 实体对象集合 |
int | batchSize | 插入批次数量 |
SaveOrUpdate
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
类型 | 参数名 | 描述 |
---|---|---|
T | entity | 实体对象 |
Collection | entityList | 实体对象集合 |
int | batchSize | 插入批次数量 |
Wrapper | updateWrapper | 实体对象封装操作类 UpdateWrapper |
Remove
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
类型 | 参数名 | 描述 |
---|---|---|
Serializable | id | 主键ID |
Map<String, Object> | columnMap | 表字段 map 对象 |
Collection<? extends Serializable> | idList | 主键ID列表 |
Wrapper | queryWrapper | 实体包装类 QueryWrapper |
Update
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
类型 | 参数名 | 描述 |
---|---|---|
Wrapper | updateWrapper | 实体对象封装操作类 UpdateWrapper |
T | entity | 实体对象 |
Collection | entityList | 实体对象集合 |
int | batchSize | 更新批次数量 |
Get
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
类型 | 参数名 | 描述 |
---|---|---|
Serializable | id | 主键ID |
Wrapper | queryWrapper | 实体对象封装操作类 QueryWrapper |
boolean | throwEx | 有多个 result 是否抛出异常 |
T | entity | 实体对象 |
Function<? super Object, V> | mapper | 转换函数 |
执行 SQL 分析打印
p6spy 依赖引入
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
application.yml 配置:
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver #com.mysql.cj.jdbc.Driver
url: jdbc:p6spy:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
type-enums-package: com.blb.mybatisplus2.enums
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1
id-type: auto
type-aliases-package: com.blb.mybatisplus2.entity
mapper-locations: classpath:/mapper/*.xml
spy.properties 配置:
#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
数据安全保护
防止删库跑路
得到16位随机秘钥
@Test
void test(){
String randomKey = AES.generateRandomKey();
System.out.println(randomKey);
}
//8f2a9a07aa736fe1
生成的自己好好保管
void test1(){
String url=AES.encrypt("jdbc:p6spy:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "8f2a9a07aa736fe1");
String username=AES.encrypt("root", "8f2a9a07aa736fe1");
String password=AES.encrypt("123456", "8f2a9a07aa736fe1");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
r7l7pDB3KRcR9CjOTveeosDKOgteIJFyTdEovVzFS6dX63ci6hMFEtWDwI5bspFs9l2Mw2SV4AtKD4m+jbyWO3+lWx0UtbUnyrRjsX1Mg+kGC1U5G3RtYhYOM5M4KJY5gnKPzhjkoFA2fxeq53MQaA==
JI3YNxsn9VTdM2CWgBh9aA==
MO6io1cTbl9CKVT5SFdsEA==
YML 配置:
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver #com.mysql.cj.jdbc.Driver
url: mpw:r7l7pDB3KRcR9CjOTveeosDKOgteIJFyTdEovVzFS6dX63ci6hMFEtWDwI5bspFs9l2Mw2SV4AtKD4m+jbyWO3+lWx0UtbUnyrRjsX1Mg+kGC1U5G3RtYhYOM5M4KJY5gnKPzhjkoFA2fxeq53MQaA==
username: mpw:JI3YNxsn9VTdM2CWgBh9aA==
password: mpw:MO6io1cTbl9CKVT5SFdsEA==
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
type-enums-package: com.blb.mybatisplus2.enums
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1
id-type: auto
type-aliases-package: com.blb.mybatisplus2.entity
mapper-locations: classpath:/mapper/*.xml
启动时要加上参数
--mpw.key=8f2a9a07aa736fe1
MyBatisPlus 代码生成器
根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller
1.pom.xml 导入 MyBatis Plus Generator
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
Velocity(默认)、Freemarker、Beetl
2.运行main方法
package com.blb;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class Main {
public static void main(String[] args) {
//创建generator对象
AutoGenerator autoGenerator = new AutoGenerator();
//数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("123456");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
autoGenerator.setDataSource(dataSourceConfig);
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
//当前项目的绝对路径
globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");
globalConfig.setOpen(false);
globalConfig.setAuthor("dyk");
//去掉默认生成接口名字的I
globalConfig.setServiceName("%sService");
autoGenerator.setGlobalConfig(globalConfig);
//包信息
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.blb.mybatisplus");
// packageConfig.setModuleName("generator");
packageConfig.setController("controller");
packageConfig.setService("service");
packageConfig.setServiceImpl("service.impl");
packageConfig.setMapper("mapper");
packageConfig.setEntity("entity");
autoGenerator.setPackageInfo(packageConfig);
//配置策略
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setEntityLombokModel(true);
strategyConfig.setRestControllerStyle(true);
//生成部分数据库里面的表对应的实体类
strategyConfig.setInclude("user","product");
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
autoGenerator.setStrategy(strategyConfig);
autoGenerator.execute();
}
}
完整版
package com.blb;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
public class Main1 {
public static void main(String[] args) {
// 代码生成器
AutoGenerator autoGenerator = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
//获得当前项目的路径
String projectPath = System.getProperty("user.dir");
//设置生成路径
gc.setOutputDir(projectPath + "/src/main/java");
//作者
gc.setAuthor("dyk");
//代码生成后是不是要打开文件所在的文件夹
gc.setOpen(false);
//生成实体属性 Swagger2 注解
// gc.setSwagger2(true);
//会在mapper.xml生成一个基础的<ResultMap> 映射所有的字段
gc.setBaseResultMap(true);
//同文件生成覆盖
gc.setFileOverride(true);
//实体类名直接用表名 %s=表名
gc.setEntityName("%s");
//mapper接口名
gc.setMapperName("%sMapper");
//mapper.xml文件名
gc.setXmlName("%sMapper");
//业务逻辑接口名
gc.setServiceName("%sService");
//业务逻辑实现类名
gc.setServiceImplName("%sServiceImpl");
//将全局配置设置到 AutoGenerator
autoGenerator.setGlobalConfig(gc);
//数据源
DataSourceConfig dsc = new DataSourceConfig();
//设置数据库类型
dsc.setDbType(DbType.MYSQL);
//连接的url
dsc.setUrl("jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
//数据库用户名
dsc.setUsername("root");
//数据库密码
dsc.setPassword("123456");
//数据库驱动
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
//将数据源配置设置到 AutoGenerator
autoGenerator.setDataSource(dsc);
//包信息
PackageConfig pc = new PackageConfig();
//包名
pc.setParent("com.blb");
//设置模块名
// pc.setModuleName("generator");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("mapper");
pc.setEntity("entity");
autoGenerator.setPackageInfo(pc);
//配置策略
StrategyConfig strategyConfig = new StrategyConfig();
//表名的生成策略:下划线转驼峰
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
//列名的生成策略:下划线转驼峰
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
//支持lombok注解
strategyConfig.setEntityLombokModel(true);
//在controller类上是否生成@Restcontroller
strategyConfig.setRestControllerStyle(true);
//生成部分数据库里面的表对应的实体类,生成的表名
strategyConfig.setInclude("user","product");
//按前缀生成表
//strategyConfig.setLikeTable("tbl_");
//设置表替换前缀
//strategyConfig.setTablePrefix("tbl_");
autoGenerator.setStrategy(strategyConfig);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 模板引擎是 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/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
autoGenerator.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
//让已有的xml生成置空
templateConfig.setXml(null);
autoGenerator.setTemplate(templateConfig);
//执行生成
autoGenerator.execute();
}
}
package com.blb;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
import java.util.ArrayList;
/**
* @author
* @since 2018/12/13
*/
public class CodeGenerator {
@Test
public void run() {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir("D:\\shixun\\blb_parent\\service\\service_edu" + "/src/main/java");
gc.setAuthor("dyk");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
//UserServie
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ASSIGN_ID); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/blb_edu?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("eduservice"); //模块名
//包 com.atguigu.eduservice
pc.setParent("com.blb");
//包 com.atguigu.eduservice.controller
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_teacher");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
// strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
strategy.setLogicDeleteFieldName("is_deleted"); // 逻辑删除字段名
strategy.setEntityBooleanColumnRemoveIsPrefix(true); //去掉布尔值is_前缀
strategy.setRestControllerStyle(true); //restful api风格控制器
// 自动填充 TableFill
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}