一. 集成

pom.xml

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

application.yml

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/deco?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
username: root
password: 123456 mybatis-plus:
mapper-locations: /mapper/*.xml,/mapper/**/*.xml
configuration:
map-underscore-to-camel-case: false

UserMapper.xml

<?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.study.demo.mybatisplus.mapper.UserMapper"> </mapper>

UserMapper.java

@Repository
public interface UserMapper extends BaseMapper<User> { }

User.java

@TableName("user")
public class User extends Model<User> {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
private SexEnum sex;
......
}

SexEnum.java

public enum SexEnum {
Male("Male", "男"),
Female("Female", "女");
private String code;
private String desc;
......
}
MybatisplusApplication.java
@SpringBootApplication
@MapperScan("com.study.demo.mybatisplus")
public class MybatisplusApplication {
public static void main(String[] args){
SpringApplication.run(MybatisplusApplication.class, args);
}
}

Service 我这里省略掉了.

到这里位置, 已经可以使用了. 在测试方法里面点一下:

可以看到, 这里自带了很多方法. 这样在单表操作的时候, 就不需要我们自己写方法了, 用 mybatis-plus 提供的方法, 还是比较省时间的.

二. pageSearch

mybatis-plus在我使用的这个版本里面, 是带有分页功能的, 但是需要进行一个配置:

@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}

有了这个配置之后, 就可以使用自带的 selectPage() 方法了. 测试方法:

@Test
public void testSelect(){
System.out.println("page query");
Page page = new Page(1, 5);
IPage pageList = userMapper.selectPage(page, new QueryWrapper<User>().eq("age", 11));
System.out.println(pageList);
}

打印日志:

page query
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65bb9029] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.jdbc.JDBC4Connection@566d0c69] will not be managed by Spring
JsqlParserCountOptimize sql=SELECT id,name,age,email,sex FROM user WHERE age = ?
==> Preparing: SELECT COUNT(1) FROM user WHERE age = ?
==> Parameters: 11(Integer)
<== Columns: COUNT(1)
<== Row: 11
==> Preparing: SELECT id,name,age,email,sex FROM user WHERE age = ? LIMIT 0,5
==> Parameters: 11(Integer)
<== Columns: id, name, age, email, sex
<== Row: 2, uxnwx, 11, uxnwx@qq.com, Female
<== Row: 10, qksyk, 11, qksyk@qq.com, Female
<== Row: 11, 5gffb, 11, 5gffb@qq.com, Female
<== Row: 12, lum96, 11, lum96@qq.com, Male
<== Row: 13, 4odsz, 11, 4odsz@qq.com, Female
<== Total: 5

三. UpdateAllColumnById()

mybatis-plus 2.x的时候还有这个方法, 但是3.x的时候, 把这个方法干掉了. 那要么在使用这个方法的时候, 自己写一个, 要么就是写一个通用的.

//MyBaseMapper.java
public interface MyBaseMapper<T> extends BaseMapper<T> {
void updateAllColumnById(@Param(Constants.ENTITY) T entity);
} //UpdateAllColumnById.java
public class UpdateAllColumnById extends AbstractMethod {
private static Logger log = LoggerFactory.getLogger(UpdateAllColumnById.class); @Override
public MappedStatement injectMappedStatement(final Class<?> mapperClass, final Class<?> modelClass, final TableInfo tableInfo) {
MySqlMethod sqlMethod = MySqlMethod.UPDATE_ALL_COLUMN_BY_ID; // 反射修改fieldFill值为update
final List<TableFieldInfo> fieldList = tableInfo.getFieldList();
for (final TableFieldInfo tableFieldInfo : fieldList) {
final Class<? extends TableFieldInfo> aClass = tableFieldInfo.getClass();
try {
final Field fieldFill = aClass.getDeclaredField("fieldFill");
fieldFill.setAccessible(true);
fieldFill.set(tableFieldInfo, FieldFill.UPDATE);
}
catch (final NoSuchFieldException e) {
log.error("获取fieldFill失败", e);
}
catch (final IllegalAccessException e) {
log.error("设置fieldFill失败", e);
}
} final String sql = String.format(sqlMethod.getSql(),
tableInfo.getTableName(),
this.sqlSet(false, false, tableInfo, Constants.ENTITY_SPOT),
tableInfo.getKeyColumn(),
Constants.ENTITY_SPOT + tableInfo.getKeyProperty(),
//sqlWhereEntityWrapper(tableInfo)
new StringBuilder("<if test=\"et instanceof java.util.Map\">")
.append("<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">")
.append(" AND ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}")
.append("</if></if>")
);
final SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
return this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
} //LogicUpdateAllColumnById.java
public class LogicUpdateAllColumnById extends AbstractLogicMethod { private static Logger log = LoggerFactory.getLogger(LogicUpdateAllColumnById.class); @Override
public MappedStatement injectMappedStatement(final Class<?> mapperClass, final Class<?> modelClass, final TableInfo tableInfo) {
final String sql;
final boolean logicDelete = tableInfo.isLogicDelete();
final SqlMethod sqlMethod = SqlMethod.LOGIC_UPDATE_ALL_COLUMN_BY_ID;
final StringBuilder append = new StringBuilder("<if test=\"et instanceof java.util.Map\">")
.append("<if test=\"et.").append(OptimisticLockerInterceptor.MP_OPTLOCK_VERSION_ORIGINAL).append("!=null\">")
.append(" AND ${et.").append(OptimisticLockerInterceptor.MP_OPTLOCK_VERSION_COLUMN)
.append("}=#{et.").append(OptimisticLockerInterceptor.MP_OPTLOCK_VERSION_ORIGINAL).append(StringPool.RIGHT_BRACE)
.append("</if></if>");
if (logicDelete) {
append.append(tableInfo.getLogicDeleteSql(true, false));
} // 反射修改fieldFill值为update
final List<TableFieldInfo> fieldList = tableInfo.getFieldList();
for (final TableFieldInfo tableFieldInfo : fieldList) {
final Class<? extends TableFieldInfo> aClass = tableFieldInfo.getClass();
try {
final Field fieldFill = aClass.getDeclaredField("fieldFill");
fieldFill.setAccessible(true);
fieldFill.set(tableFieldInfo, FieldFill.UPDATE);
} catch (final NoSuchFieldException e) {
log.error("获取fieldFill失败", e);
} catch (final IllegalAccessException e) {
log.error("设置fieldFill失败", e);
} }
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
this.sqlSet(logicDelete, false, tableInfo, Constants.ENTITY_SPOT),
tableInfo.getKeyColumn(), Constants.ENTITY_SPOT + tableInfo.getKeyProperty(),
append);
final SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
return this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
} //MySqlMethod.java
public enum MySqlMethod {
UPDATE_ALL_COLUMN_BY_ID("updateAllColumnById", "根据ID 选择修改数据", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"); private final String method;
private final String desc;
private final String sql; MySqlMethod(String method, String desc, String sql) {
this.method = method;
this.desc = desc;
this.sql = sql;
} public String getMethod() {
return method;
} public String getDesc() {
return desc;
} public String getSql() {
return sql;
}
} //CustomSqlInjector.java
public class CustomSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
return Stream.of(
new Delete(),
new DeleteBatchByIds(),
new DeleteById(),
new DeleteByMap(),
new Insert(),
new SelectBatchByIds(),
new SelectById(),
new SelectByMap(),
new SelectCount(),
new SelectList(),
new SelectMaps(),
new SelectMapsPage(),
new SelectObjs(),
new SelectOne(),
new SelectPage(),
new Update(),
new UpdateById(),
new UpdateAllColumnById()
).collect(Collectors.toList());
}
} //CustomLogicSqlInjector.java
public class CustomLogicSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
return Stream.of(
new Insert(),
new LogicDelete(),
new LogicDeleteByMap(),
new LogicDeleteById(),
new LogicDeleteBatchByIds(),
new LogicUpdate(),
new LogicUpdateById(),
new LogicUpdateAllColumnById(),
new LogicSelectById(),
new LogicSelectBatchByIds(),
new LogicSelectByMap(),
new LogicSelectOne(),
new LogicSelectCount(),
new LogicSelectMaps(),
new LogicSelectMapsPage(),
new LogicSelectObjs(),
new LogicSelectList(),
new LogicSelectPage()
).collect(Collectors.toList());
}
}

接下来就是进行配置:

@Bean
public ISqlInjector sqlInjector() {
return new CustomSqlInjector();
}

UserMapper.java也需要跟着修改一下:

@Repository
public interface UserMapper extends MyBaseMapper<User> { }

这样, 就可以使用 UpdateAllColumnById() 这个方法了. 同样的, 如果有别的通用方法想加, 也可以通过以上方法进行修改新增即可.


mybatis-plus - 初识的更多相关文章

  1. mybatis入门--初识mybatis

    初识mybatis 今天,一起来说说mybits这个框架吧.这是一个持久层的框架.之前叫做ibatis.所以,在它的代码中出现ibatis这个词的时候,不要感到惊讶.不是写错了,它确实就是这个样子的. ...

  2. 【MyBatis】-----初识【MyBatis】

    一.核心配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration ...

  3. 初识mybatis(二)

    上篇博客我们介绍通过Java代码来创建mybatis的配置文件,港真,这种方式看起来有意思实际在开发中用的并不多,mybatis的配置还是以xml配置为主,本文我们就来看看如何通过xml文件来配置my ...

  4. MyBatis 框架系列之基础初识

    MyBatis 框架系列之基础初识 1.什么是 MyBatis MyBatis 本是 apache 的一个开源项目 iBatis,后改名为 MyBatis,它 是一个优秀的持久层框架,对 jdbc 的 ...

  5. MyBatis For .NET学习- 初识MyBatis

    MyBatis的框架. Introduction MyBatis本是apache的一个开源项目iBatis,2010年这个项目由 apache software foundation迁移到了googl ...

  6. 初识Mybatis之工程搭建

    简介:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 ...

  7. MyBatis学习01(初识MyBatis和CRUD操作实现)

    1.初识MyBatis 环境说明: jdk 8 + MySQL 5.7.19 maven-3.6.1 IDEA 学习前需要掌握: JDBC MySQL Java 基础 Maven Junit 什么是M ...

  8. 初识Mybatis框架,实现增删改查等操作(动态拼接和动态修改)

    此第一次接触Mybatis框架确实是有点不适应,特别是刚从Hibernate框架转转型过来,那么为什么要使用Mybatis框架,Mybatis框架和Hibernate框架又有什么异同呢? 这个问题在我 ...

  9. 初识MyBatis

    ORM:对象关系映射,它只是一种规则. 像MyBatis,Hibernate对jdbc进行了封装. 第一章 回顾JDBC开发 1.优点:简单易学,上手快,非常灵活构建SQL(自己写的),效率高.2.缺 ...

  10. 初识Mybatis框架,实现增删改查等操作

    此第一次接触Mybatis框架确实是有点不适应,特别是刚从Hibernate框架转转型过来,那么为什么要使用Mybatis框架,Mybatis框架和Hibernate框架又有什么异同呢? 这个问题在我 ...

随机推荐

  1. ajax-属性、原理、实现html5进度条上传文件

    一.远古ajax实现方式如下: 1.前端请求后台,后台设置返回 http状态码204 2.运用img图片(或css/javascript等)的加载机制,请求后台 3.post提交数据,运用iframe ...

  2. Jenkins-Publish Over SSH插件

    插件安装 打开Jenkins的“系统管理>管理插件”,选择“可选插件”,在输入框中输入“Publish over SSH”进行搜索,如果搜索不到可以在“已安装”里确认是否已经安装过.在搜索结果中 ...

  3. Period 时间坑

    jdk1.8 的Period Period between = Period.between( LocalDate.parse("2018-01-01 00:00:00", Dat ...

  4. 树莓派3b 换国内源 更新源

    在国内要更新源的时候,因为是国外的源,总会出现网速太慢的问题, 以下是对于安装了,2017-11-29-raspbian-stretch 系统源 更换最好用root登陆操作 sudo passwd r ...

  5. flex 属性

    一.flex-direction(元素排列方向) 1.flex-direction:row://从左到右排列 2.flex-direction:column://从上往下排列 二.flex-wrap( ...

  6. Docker最全教程——从理论到实战(二十)

    前言 各种编程语言均有其优势和生态,有兴趣的朋友完全可以涉猎多门语言.在平常的工作之中,也可以尝试选择相对适合的编程语言来完成相关的工作. 在团队技术文档站搭建这块,笔者尝试了许多框架,最终还是选择了 ...

  7. Log4net实用说明

    Log4net实用说明 Appender Filter Layout Logger ObjectRender Repository PatterLayout格式化字符表 配置文件说明 Appender ...

  8. bookdown学习笔记

    主要参考大佬谢益辉的bookdown学习笔记 https://bookdown.org/yihui/bookdown/pandoc.html 灰常之详细 然后clone了他写好的小demo,准备自己试 ...

  9. Silver Cow Party POJ - 3268

    #include<iostream> #include<queue> #include<cstring> using namespace std; +,INF=0x ...

  10. UTF自动化测试工具

    自UFT推出后,QTP慢慢退出历史舞台 UFT测试的基本流程:录制测试脚本—-编辑测试脚本—-调试测试脚本—-运行测试脚本—-分析测试结果 UFT(QTP)介绍   http://blog.csdn. ...