1. Mybaits-plus实战(一)
1.1. 快速开始
1.1.1. 配置文件
# 扫描位置
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.beikbank.fund.entity
# 逻辑删除指定值
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
# 下划线转驼峰
mybatis-plus.configuration.map-underscore-to-camel-case=true
1.1.2. 代码生成器
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.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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MybatisPlusGenerator {
/**
* <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.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("laoliangliang");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setDateType(DateType.ONLY_DATE);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("xxx");
dsc.setPassword("xxxx");
dsc.setTypeConvert(new MySqlTypeConvert());
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setModuleName("fund");
pc.setParent("com.beikbank");
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) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
String entityName = tableInfo.getEntityName();
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + entityName + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
// strategy.setSuperEntityColumns(new String[]{"create_time","update_time","status","del_flag"});
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// strategy.setSuperControllerClass("com.beikbank.fund.common.BaseController");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
// strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("t_uls_");
strategy.setLogicDeleteFieldName("del_flag");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
- 这是我的配置,把包名,前缀等等改了,试验下就知道了,或者直接看官网
https://mp.baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B
1.1.3. 代码配置
@Configuration
@MapperScan("com.beikbank.fund.mapper*")
public class MybatisPlusConfig {
/***
* plus 的性能优化
* @return
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/*<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->*/
performanceInterceptor.setMaxTime(1000);
/*<!--SQL是否格式化 默认false-->*/
performanceInterceptor.setFormat(false);
return performanceInterceptor;
}
/**
* @Description : mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
// 配置数据源
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
/**
* 逻辑删除注入
*/
@Bean
public LogicSqlInjector logicSqlInjector(){
return new LogicSqlInjector();
}
}
- 用来扫描指定位置mapper,逻辑删除注入,事务,数据库配置等
1.2. 配置druid
1.2.1. 代码配置
/**
* @author laoliangliang
* @date 2019/4/25 17:18
*/
@Configuration
public class DruidConfig {
/**
* 配置监控服务器
* @return 返回监控注册的servlet对象
* @author SimpleWu
*/
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 添加IP白名单
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
// servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
// 添加控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "SimpleWu");
servletRegistrationBean.addInitParameter("loginPassword", "123456");
// 是否能够重置数据
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* 配置服务过滤器
*
* @return 返回过滤器配置对象
*/
@Bean
public FilterRegistrationBean statFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则
filterRegistrationBean.addUrlPatterns("/*");
// 忽略过滤格式
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
return filterRegistrationBean;
}
}
1.2.2. 配置文件
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=xxx
spring.datasource.password=xxxx
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
1.3. 返回对象注入
1.3.1. 代码
/**
* 在数据插入更新后填充
* @author laoliangliang
* @date 2019/4/25 17:37
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
1.3.2. 作用
- 对公共字段返回时可以加一些信息,在插入更新后直接存放到对应字段中
1.4. 启动
1.4.1. 查看Druid监控台
- 输入
localhost:8080/druid
即可访问,密码为配置文件里所配loginUsername
和loginPassword
1.4.2. 测试mybatis plus
1.4.2.1. 编写controller层(前提已经用生成器生成了一张表数据)
- 我随意写了些测试
/**
* <p>
* 前端控制器
* </p>
*
* @author laoliangliang
* @since 2019-04-25
*/
@RestController
@RequestMapping("/fund/daily-price")
public class DailyPriceController {
@Autowired
private IDailyPriceService dailyPriceService;
@GetMapping("/get")
public IPage<DailyPrice> test(){
return dailyPriceService.getBaseMapper().selectPage(new Page<>(1, 10), new QueryWrapper<>());
}
@GetMapping("/get2")
public IPage get2(){
DailyPrice dailyPrice = new DailyPrice();
return dailyPrice.selectPage(new Page<DailyPrice>(1, 10), new QueryWrapper<>());
}
@GetMapping("/delete")
public int delete(){
return dailyPriceService.getBaseMapper().deleteById(1112);
}
@GetMapping("/delete2")
public int delete2(){
DailyPrice dailyPrice = new DailyPrice();
dailyPrice.setDailyPriceId(1112L);
return dailyPrice.deleteById()?1:0;
}
@GetMapping("/insert")
public int insert(){
DailyPrice dailyPrice = new DailyPrice();
dailyPrice.setCurrentPrice(new BigDecimal("456"));
return dailyPriceService.getBaseMapper().insert(dailyPrice);
}
@GetMapping("/insert2")
public int insert2(){
DailyPrice dailyPrice = new DailyPrice();
dailyPrice.setCurrentPrice(new BigDecimal("456"));
dailyPrice.setCurrentTime(new Date());
return dailyPrice.insert()?1:0;
}
}
- 分别用了AR模式和普通模式,测试都成功
除了官网,还有个gitee的代码说明也可以参考
https://baomidou.gitee.io/mybatis-plus-doc/#/quick-start