一. 集成

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. 【NLP】暑假课作业1 - 中文分词(前向匹配算法实现)

    作业任务: 使用98年人民日报语料库进行中文分词训练及测试. 作业输入: 98年人民日报语料库(1998-01-105-带音.txt),用80%的数据作为训练集,20%的数据作为验证集. 运行环境: ...

  2. 数字孪生 VS 平行系统

    数字孪生和平行系统作为新兴技术,在解决当今人工智能邻域面临的信息量大,干扰信息不确定因素多,与人的参与沟通更加紧密,人机互动更加重视,为了使人们有更好的体验人工智能带来的便利,急需推动信息物理社会的高 ...

  3. Spring Boot源码(一):去除web.xml

    访问https://spring.io/ spring boot中: public class MyWebApplicationInitializer implements WebApplicatio ...

  4. gulp常用插件之bower使用

    更多gulp常用插件使用请访问:gulp常用插件汇总 bower这是一款客户端技术的软件包管理器,它可用于搜索.安装和卸载如JavaScript.HTML.CSS之类的网络资源. 更多使用文档请点击访 ...

  5. 使用FDATOOL生成xilinx中FIR滤波器IP核的系数

    1.在MATLAB命令窗口输入fdatool后回车,打开“Filter Designer & Analysis Tool”工具界面: 2.点击左下角的Set quantization para ...

  6. PAT - A1073

    1073 Scientific Notation (20point(s)) 小数点移动的边界条件 小数点左移 超过数据左边界 小数点右移 未超过数据右边界 超过数据右边界 +0.1E+2 --> ...

  7. JS 百度地图路书---动态路线

    JS 百度地图路书---动态路线 <!DOCTYPE html> <head> <meta http-equiv="Content-Type" con ...

  8. Mysql分库分表导出导入和数据量统计测试

    需求:添加创建了分库分表后,业务可能将数据已经写入,但未来得及接入到otter汇总库.接入汇总库前需要初始化这部分数据. 1.导出 ip_port_list ) len=${#ip_port_list ...

  9. linux-redis cluster集群(redis5.x)

    1.查看redis安装目录: [root@iZwz97y9qoykzzotubitq3Z redis-5.0.5]# lltotal 472-rw-rw-r-- 1 root root 106874 ...

  10. AcWing 6. 多重背包问题 III

    //f[i,j] 所有只从前i块能量石中选,且总体积恰好为j的方案数 #include <iostream> #include <algorithm> #include < ...