一. 集成

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. phpcms v9全站点击量排行代码

    前台: <ul> {pc:content action="sitehits" siteid="1" num="10" order ...

  2. Swagger2 @ApiIgnore注解忽略接口在swagger-ui.html中显示

    果项目中定义了一个controller,但是我们又不想把这个接口在swagger-ui.html中体现出来怎么办?不要着急,Swagger2已经替我们想到了这个问题,只要把@ApiIgnore放到你想 ...

  3. 关于GET和POST请求的区别,最通俗全面的回答

    GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通过request body传递参数. 你可能自己 ...

  4. 剑指offer-面试题14-剪绳子-贪婪算法

    /* 题目: 给定一个长度为n的绳子,把绳子剪为m段,(n>1,m>1) 求各段绳子乘积的最大值. */ /* 思路: 贪婪算法. 当绳子的长度大于5时,尽可能多的剪长度为3的绳子:当剩下 ...

  5. gulp常用插件之yargs使用

    更多gulp常用插件使用请访问:gulp常用插件汇总 yargs这是一款通过解析参数并生成优雅的用户界面来帮助您构建交互式命令行工具.处理命令行参数的通用解决方案,只要一句代码 var args = ...

  6. Django-模型(二)

    条件查询 字段查询 实现sql中where的功能,调用过滤器filter().exclude().get(),下面以filter()为例. 通过"属性名_id"表示外键对应对象的i ...

  7. [Err] 1248 - Every derived table must have its own alias

    问题描述 [Err] 1248 - Every derived table must have its own alias 问题原因 这句话的意思是说每个派生出来的表都必须有一个自己的别名 我的Mys ...

  8. python django项目的搭建及初始配置

    1.创建项目并创建应用 django-admin startproject my_project # 创建项目python manage.py startapp my_app # 创建应用 1.1 项 ...

  9. linux--nginx学习

    nginx 1.nginx安装编译 1.yum install nginx(自动解决依赖) 2.源代码编译安装(优秀,自由选择软件版本,自定义第三方功能比如开启https) 3.rpm手动安装(垃圾) ...

  10. 【你不知道的javaScript 上卷 笔记4】javaScript 中闭包的一些运用

    什么是闭包 闭包是javaScript语言的一种特性,在 javaScript 中以函数作为承接单元.当函数可以记住并访问所在的词法作用域时,就产生了闭包,即使函数是在当前词法作用域之外执行. fun ...