一. 集成
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() 這個方法了. 同樣的, 如果有別的通用方法想加, 也可以通過以上方法進行修改新增即可.