MyBatis-Plus简称MP是对Mybatis的增强,只做增强不做改变,所以Mybatis原生的功能不受任何影响。
安装插件
安装完该插件后Mapper接口前和Mapper.xml前就会出现MP的标识,当点击接口前面的标识的时候就会跳转到对应的xml文件中去
首先初始化数据库:在resources目录下创建sql文件夹,然后在下面创建myproject.sql文件,项目加载的时候会自动加载初始化数据库
spring:
datasource:
username: root
password: root
url:jdbc:mysql://10.121.51.51:3306/txl_edu?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 项目启动时会自动初始化数据库运行数据库sql脚本文件
schema: classpath:sql/myproject.sql
initialization-mode: alaways #never
根据id查询
注:
logging:
level:
root: info
com.txl.mapper: debug
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
注:我们可以自己设置主键的生成策略
@TableId(value=“id”,type=“IdType.AUTO”)
private Integer id;
调用MP的insert方法插入数据之后,会将插入数据的id自动同步到实体中,不需要我们做额外的操作。
注意该方法的参数是实体对象
根据id删除
selectByMap(null):查询所有数据
map.put(“id”,6);
slectByMap(map);
@TableField(exist=false)
private xxx xxxx;
我们自己的service接口需要实现Iservice
我们自己的service实现类需要继承ServiceImpl
根据id查询
id存在就是修改操作,否则为插入操作
根据id批量删除,底层是通过id IN (?,?,?)
list = Arrays.asList(11,22,5);
removeByIds(list);
根据id批量查询
list = Arrays.asList(11,22,5);
listByIds(list);
需要配置分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MyBatisPlusInterceptor();
//里面需要指定数据库的方言
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
然后就可以进行分页查询了
// 第一个参数为当前页,第二个参数为每页显示几条
Ipage iPage = new IPage(1,2);
Ipage page = service.page(iPage);
List records = page.getRecords();
在resources包下新建mapper包,里面新建xml映射文件
public interface TeacherMapper extends BaseMapper {
public IPage getByName(IPage page,String name);
}
接下来我们就可以调用了
Ipage iPage = new IPage(1,2);
IPage page = mapper.getByName(iPage,“aaa”);
注:
1.如果需要分页,只要在mapper接口上传递分页参数然后在用分页对象接收即可。
2.MP默认加载resources目录下的mapper文件夹下的xml文件,如果地址不一致需要配置
mybatis-plus.mapper-locations=classpath:/daoxml/*.xml
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.ne("parent_id", 0);
queryWrapper.between("age",10,20);
List teachers = baseMapper.selectList(queryWrapper);
MyBatis-Plus的主键可以在spring的配置文件中统一配置
mybatis-plus.global-config.db-config.id-type=auto
物理删除是将数据从磁盘上删除
逻辑删除是数据还在,但是状态是不可用
添加逻辑删除字段:
private Integer enabled;
在数据库添加相应的字段
enabled int default 1
添加注解
//官方默认删除用1表示未删除用0表示,可以修改过来
@TableLogic(value=“1”,delval=“0”)
private Integer enabled;
此注解标注只对这一个字段对应的表逻辑删除,如果想全局进行逻辑删除,则需要在spring的配置文件中配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: endabled #全局逻辑删除的字段
logic-delete-value:1 #逻辑已删除的默认值默认值,官方已删除默认是1
logic-not-delete-value: 0 #逻辑未删除的默认值
List item
数据库两个字段
gmt_create datetime 默认CURRENT_TIMESTAMP
gmt_update datetime 默认CURRENT_TIMESTAMP
CURRENT_TIMESTAMP就是每次操作时更新为当前时间,这是从数据库层面自动填充(mysql5.6以下不支持)
在实体类中添加相应的字段
private Date gmtCreate;
private Date gmtUpdate;
添加注解
@TableField(fill=FieldFill.INSERT)
private Date gmtCreate;
@TableField(fill=FieldFill.INSERT_UPDATE)
private Date gmtUpdate;
需要注入MetaObjectHandler的Bean
@Component
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("开始自动填充");
this.setFieldValByName("gmtCreate",new Date(),metaObject);
this.setFieldValByName("gmtUpdate",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("开始自动填充");
this.setFieldValByName("gmtUpdate",new Date(),metaObject);
}
}
注:需要MP的版本在3.1.0以上
引入依赖
修改数据库驱动
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
注意!
driver-class-name 为 p6spy 提供的驱动类
url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
打印出sql为null,在excludecategories增加commit
批量操作不打印sql,去除excludecategories中的batch
批量操作打印重复的问题请使用MybatisPlusLogFactory (3.2.1新增)
该插件有性能损耗,不建议生产环境使用。
3.3.2 开始支持
1.得到16位随机秘钥
2.加密对应的数据
3.使用
java -jar xxx.jar --mpw.key=39ewruiofaf --spring.profiles.active=prod
为了解决线程安全问题
悲观锁:很悲观,如果有其他线程来有可能会产生问题,所以我运行的时候其他锁必须挂起等待,整个过程数据处于锁定状态,同步锁就是悲观锁的实现。
乐观锁:在数据进行提交更新的时候再检查是否冲突,如果冲突给用户错误信息。采用版本号来控制。
1.在数据库中加入版本号字段
version int default 1
2.在实体类中添加相应的字段并添加@Version注解
private Integer version;
3.初始化乐观锁插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
说明:
String mouduleName = scanner("模块名");
String tableName= scanner("表名(多个用逗号分隔)");
AutoGenerator generator = new AutoGenerator();
//如果选择了其他模板请进行下面配置
// set freemarker engine
//generator.setTemplateEngine(new //FreemarkerTemplateEngine());
// set beetl engine
//generator.setTemplateEngine(new BeetlTemplateEngine());
// set custom engine (reference class is your custom engine class)
//generator.setTemplateEngine(new CustomTemplateEngine());
//全局配置
GlobalConfig globalConfig = new GlobalConfig();
//获取当前项目的路径--注意是父工程的路径,如果是子模块则需要加上
//("user.dir") +"/cloudos-opt*+"/src/main/java")
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
//作者
globalConfig.setAuthor("bwcg");
//代码生成后是否打开所在文件夹
globalConfig.setOpen(false);
//是否生成Swagger注解--数据库表有注释才行
globalConfig.setSwagger2(true);
//在mapper.xml中生产一个基础的会自动映射所有的字段
globalConfig.setBaseResultMap(true);
//下次生产的时候是覆盖还是增加
globalConfig.setFileOverride(true);
//指定时间的生成格式
globalConfig.setDateType(DateType.ONLY_DATE);
//设置实体类的名称默认是%sEntity %s表示表名
globalConfig.setEntityName("%s");
//默认是%sDao
globalConfig.setMapperName("%sMapper");
globalConfig.setXmlName("%sMapper");
globalConfig.setServiceName("%sService");
globalConfig.setServiceImplName("%sServiceImpl");
//将全局配置加入生成器
generator .setGlobalConfig(globalConfig);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("密码");
generator .setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setMouduleName(moduleName)
pc.setModuleName("opt");
pc.setParent("com.txl");
generator.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//表名 下划线转驼峰
strategy.setNaming(NamingStrategy.underline_to_camel);
//列名
strategy.setColumnNaming(NamingStrategy.underline_to_camel;
//实体类父类
//strategy.setSuperEntityClass("你自己的父类实体,没有就不
//用设置!");
//是否支持lombok
strategy.setEntityLombokModel(true);
//是否是@RestController
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
//要生成的表名
strategy.setInclude("user","order","stu").split(","));
//模糊生成
strategy.setLikeTable(new LikeTable("opt_"));
//驼峰转连接符 /aa/aaa_bbb /aaa/aaaBbb
strategy.setControllerMappingHyphenStyle(true);
//设置表的忽略前缀t_
strategy.setTablePrefix("dp_");
generator.setStrategy(strategy);
// 自定义配置
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 的名称会跟着发生变化!! 此配置吧mapper.xml放到resources目录下
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
//让默认的模板失效,它默认会将mapper.xml放到mapper包下
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
generator.execute();
/上面代码卸载main方法里面
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 + "!");
}
在main方法中运行就可以生成了
代码生成器
package com.txl.eduservice;
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.jupiter.api.Test;
import java.util.ArrayList;
public class CodeGenerator {
@Test
public void main1(){
//数据库前缀
String prefix = "online";
//模块名称--因为要根据业务分库,所以不同的模块会有不同的数据库
String moduleName = "edu";
//1创建代码生成器
AutoGenerator mpg = new AutoGenerator();
//2全局配置
GlobalConfig gc = new GlobalConfig();
//根据全局变量名获取项目所在的路径:service_edu项目路径,也可写绝对路径写死:G:\IdeaWorkSpace\txl-parent\service\service-edu
String projectPath = System.getProperty("user.dir");
System.out.println("system.getProperty(user.dir)+++++++++++++++:"+projectPath);
//代码的输出目录
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("txl-xyq");
//代码生成后是否将所有的目录展开
gc.setOpen(true);
//重新生成时文件是否覆盖---覆盖误点之后有可能把已经写好的代码干没了
gc.setFileOverride(true);
//去掉Service接口的首字母I,默认接口以I打头
gc.setServiceName("I%sService");
gc.setIdType(IdType.ASSIGN_ID);
//定义生成的实体中的日期类型
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
//
// /**
// * mp生成service层代码,默认接口名称第一个字母为I
// */
//
// gc.setServiceName("%sService");//去掉默认的首字母I
// gc.setIdType(IdType.ID_WORKER_STR);//主键生成策略
// gc.setDateType(DateType.ONLY_DATE);//第一生成实体类中的日期类型
// gc.setSwagger2(true);//开启swagger2模式
//
mpg.setGlobalConfig(gc);
//3数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/"+prefix+"_txl_"+moduleName+"?serverTimezone=GMT%2B8&characterEncoding=UTF-8");
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();
//src/main/java下生成的包名
pc.setParent("com.txl.service");
//最终的包名是:src/main/com.txl.service.moduleName
pc.setModuleName(moduleName);//模块名
//只能生成四层基本包
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
//5策略配置
StrategyConfig strategy = new StrategyConfig();
// //设置根据哪张表生成实体,多张表可以用逗号隔开、
// //strategy.setInclude("table1","table2","table3"....);
// //不指定就是该数据库的所有表
// strategy.setInclude("edu_teacher");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
//strategy.setTablePrefix(pc.getModuleName()+"_");//生成实体时去掉表前缀
strategy.setTablePrefix("edu_");//生成实体时去掉表前缀
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");//逻辑删除列
//生成实体时删除逻辑前缀is---生成代码如果存在包没有自动导入的情况请手动导包
strategy.setEntityBooleanColumnRemoveIsPrefix(true);
//自动填充
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
TableFill isDeleted = new TableFill("is_deleted", FieldFill.INSERT);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
tableFills.add(isDeleted);
strategy.setTableFillList(tableFills);
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
//在common模块中设置BaseEntity
strategy.setSuperEntityClass("com.txl.servicebase.entity.BaseEntity");
// 填写BaseEntity中的公共字段
strategy.setSuperEntityColumns("id", "gmt_create", "gmt_modified");
mpg.setStrategy(strategy);
//6执行
mpg.execute();
}
}