• mybatis-plus


    一. 集成

    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>
    UPDATE %s %s WHERE %s=#{%s} %s
    </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() 这个方法了. 同样的, 如果有别的通用方法想加, 也可以通过以上方法进行修改新增即可.






  • 相关阅读:
    几种类间关系:继承、实现、依赖、关联、聚合、组合及UML变现图(转)
    StarUML指导手册(转)
    hook(转)
    DancingLinks简介(转)
    (转)用宏获取函数名
    UML中关联和依赖的区别
    “智商平平”学软件(转)
    生产者消费者问题Semaphore
    [转] UML中关联、依赖、聚集等关系的异同
    最近要看的东西
  • 原文地址:https://www.cnblogs.com/elvinle/p/12317828.html
Copyright © 2020-2023  润新知