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();
} }
  1. 这是我的配置,把包名,前缀等等改了,试验下就知道了,或者直接看官网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();
}
}
  1. 用来扫描指定位置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. 对公共字段返回时可以加一些信息,在插入更新后直接存放到对应字段中

1.4. 启动

1.4.1. 查看Druid监控台

  1. 输入localhost:8080/druid即可访问,密码为配置文件里所配loginUsernameloginPassword

1.4.2. 测试mybatis plus

1.4.2.1. 编写controller层(前提已经用生成器生成了一张表数据)

  1. 我随意写了些测试
/**
* <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;
}
}
  1. 分别用了AR模式和普通模式,测试都成功

除了官网,还有个gitee的代码说明也可以参考https://baomidou.gitee.io/mybatis-plus-doc/#/quick-start

Mybaits-plus实战(一)的更多相关文章

  1. 重学 Java 设计模式:实战中介者模式「按照Mybaits原理手写ORM框架,给JDBC方式操作数据库增加中介者场景」

    作者:小傅哥 博客:https://bugstack.cn - 原创系列专题文章 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 同龄人的差距是从什么时候拉开的 同样的幼儿园.同样的小学.一样 ...

  2. 【转】mybatis实战教程(mybatis in action),mybatis入门到精通

    MyBatis 目录(?)[-] mybatis实战教程mybatis in action之一开发环境搭建 mybatis实战教程mybatis in action之二以接口的方式编程 mybatis ...

  3. mybatis实战教程(mybatis in action),mybatis入门到精通

    转自:http://www.yihaomen.com/article/java/302.htm (读者注:其实这个应该叫做很基础的入门一下下,如果你看过hibernate了那这个就非常的简单) (再加 ...

  4. mybatis实战教程(mybatis in action),mybatis入门到精通(转)

    转自:http://www.yihaomen.com/article/java/302.htm (读者注:其实这个应该叫做很基础的入门一下下,如果你看过Hibernate了那这个就非常的简单) (再加 ...

  5. mybatis完美的实战教程

    文件夹(? )[-] (读者注:事实上这个应该叫做非常基础的入门一下下,假设你看过Hibernate了那这个就非常的简单) 文章来源:http://blog.csdn.net/techbirds_ba ...

  6. MP实战系列(三)之实体类讲解

    首先说一句,mybatis plus实在太好用了! mybaits plus的实体类: 以我博客的用户类作为讲解 package com.blog.entity; import com.baomido ...

  7. 面面俱到的Java接口自动化测试实战

    第1章 接口自动化测试整体认知了解什么是接口和为什么要做接口测试.并且知道接口自动化测试应该学习哪些技术以及接口自动化测试的落地过程. 1-1 导学章节 1-2 什么是接口 1-3 为什么要做接口测试 ...

  8. 1.mybatis实战教程mybatis in action之一开发环境搭建

    转自:https://www.cnblogs.com/shanheyongmu/p/5652471.html 什么是mybatis MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框 ...

  9. 重学 Java 设计模式:实战适配器模式

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 擦屁屁纸80%的面积都是保护手的! 工作到3年左右很大一部分程序员都想提升自己的技术 ...

  10. SpringMVC+Spring+mybatis+maven+搭建多模块框架前后端分离开发框架的完整demo,拿走不谢。——猿实战02

            猿实战是一个原创系列文章,通过实战的方式,采用前后端分离的技术结合SpringMVC Spring Mybatis,手把手教你撸一个完整的电商系统,跟着教程走下来,变身猿人找到工作不是 ...

随机推荐

  1. 管理和安装 chart - 每天5分钟玩转 Docker 容器技术(168)

    安装 chart 当我们觉得准备就绪,就可以安装 chart,Helm 支持四种安装方法: 安装仓库中的 chart,例如:helm install stable/nginx 通过 tar 包安装,例 ...

  2. linux下c编程 基础

    1. 熟悉Linux系统下的开发环境 2. 熟悉vi的基本操作 3. 熟悉gcc编译器的基本原理 4. 熟练使用gcc编译器的常用选项 5 .熟练使用gdb调试技术 6. 熟悉makefile基本原理 ...

  3. spawn-fcgi运行fcgiwrap

    http://linuxjcq.blog.51cto.com/3042600/718002 标签:休闲 spawn-fcgi fcgiwarp fcgi 职场 原创作品,允许转载,转载时请务必以超链接 ...

  4. windows命令中的cd

    cd命令的作用为改变文件夹,也就是跳转目录.切换路径的意思.它后面可以接驱动器符号.完整路径和相对路径. 打开命令行窗口的时候,默认的目录位于当前用户所在的路径下,比如:C:\Users\koi\De ...

  5. 转载:python + requests实现的接口自动化框架详细教程

    转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实现的接口自动化框架详细教程 前段时间由于公司测试方向的转型,由 ...

  6. handler.go

    {         w.WriteHeader(http.StatusAccepted)     } else {         errStr := ""         for ...

  7. Dubbo中集群Cluster,负载均衡,容错,路由解析

    Dubbo中的Cluster可以将多个服务提供方伪装成一个提供方,具体也就是将Directory中的多个Invoker伪装成一个Invoker,在伪装的过程中包含了容错的处理,负载均衡的处理和路由的处 ...

  8. golang 并发模式笔记

    1.并发并不是并行,前者是优先对时间片的抢占,后者是真多核. go中多线程时直接要求并行的方法是: 亦不可滥用,CPU密集型,并发度很高的场景适用. 2.go起的协程 3. function that ...

  9. Django rest_framework快速入门

    一.什么是REST 面向资源是REST最明显的特征,资源是一种看待服务器的方式,将服务器看作是由很多离散的资源组成.每个资源是服务器上一个可命名的抽象概念.因为资源是一个抽象的概念,所以它不仅仅能代表 ...

  10. bzoj 2829 计算几何

    将每张卡四个角的圆心跑graham出正常凸包,再加上一个圆就好了. 要注意先输入的是x,找点时三角函数瞎换就过了.. #include<cstdio> #include<cstrin ...