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. java算法之超级丑数

    问题描述: 写一个程序来找第 n 个超级丑数. 超级丑数的定义是正整数并且所有的质数因子都在所给定的一个大小为 k 的质数集合内. 比如给你 4 个质数的集合 [2, 7, 13, 19], 那么 [ ...

  2. 洛谷 P1490 解题报告

    P1490 买蛋糕 题目描述 野猫过生日,大家当然会送礼物了(咳咳,没送礼物的同志注意了哈!!),由于不知道送什么好,又考虑到实用性等其他问题,大家决定合伙给野猫买一个生日蛋糕.大家不知道最后要买的蛋 ...

  3. webpack,配置,上手,例子

    1.webpack是什么? 2.为什么要用webpack? 3.怎么用webpack? webpack是什么? 答:webpack是前端模块化应用和开发的打包工具,解决前端模块依赖的工具.打包所有的脚 ...

  4. Git分支合并冲突解决(续)

    接Git分支合并冲突解决,在使用rebase合并冲突情况下,如果不小心,执行完add后执行了commit,此时本地仓库HEAD处于游离态(即HEAD指向未知的分支),如何解决? 解决方法 (1)此时, ...

  5. swagger-codegen自动生成代码工具的介绍与使用

    一.Swagger Codegen简介 Swagger Codegen是一个开源的代码生成器,根据Swagger定义的RESTful API可以自动建立服务端和客户端的连接.Swagger Codeg ...

  6. 剑指Offer常见问题整理

    1 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数.(来自牛客网,剑指offer) ...

  7. springMVC框架在js中使用window.location.href请求url时IE不兼容问题解决

    是使用springMVC框架时,有时候需要在js中使用window.location.href来请求url,比如下面的路径: window.location.href = 'forecast/down ...

  8. ViewDragHelper实战 自己打造Drawerlayout

    转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/47396187: 本文出自:[张鸿洋的博客] 一.概述 中间拖了蛮长时间了,在上 ...

  9. QM

    答案: C 解题: 1. PV = 1,2 / 11% = 10.91 NPV = PV(inflow)-PV(outflow) = 10.91 - 8 = 2.91 2. IRR : NPV = 0 ...

  10. bzoj 3759 Hungergame 博弈论+线性基

    和nim游戏类似 易证必败状态为:当前打开的箱子中石子异或和为0,没打开的箱子中不存在一个子集满足异或和为0 因为先手无论是取石子还是开箱子,后手都可以通过取石子来使状态变回原状态 所以只需判定是否有 ...