Search in sources :

Example 21 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project mybatis-plus-samples by baomidou.

the class MybatisPlusConfig method globalConfig.

@Bean
public GlobalConfig globalConfig() {
    GlobalConfig conf = new GlobalConfig();
    conf.setDbConfig(new GlobalConfig.DbConfig().setColumnFormat("`%s`"));
    DefaultSqlInjector logicSqlInjector = new DefaultSqlInjector() {

        /**
         * 注入自定义全局方法
         */
        @Override
        public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
            List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
            // 不要逻辑删除字段, 不要乐观锁字段, 不要填充策略是 UPDATE 的字段
            methodList.add(new InsertBatchSomeColumn(t -> !t.isLogicDelete() && !t.isVersion() && t.getFieldFill() != FieldFill.UPDATE));
            // 不要填充策略是 INSERT 的字段, 不要字段名是 column4 的字段
            methodList.add(new AlwaysUpdateSomeColumnById(t -> t.getFieldFill() != FieldFill.INSERT && !t.getProperty().equals("column4")));
            return methodList;
        }
    };
    conf.setSqlInjector(logicSqlInjector);
    return conf;
}
Also used : OptimisticLockerInnerInterceptor(com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor) InsertBatchSomeColumn(com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn) AbstractMethod(com.baomidou.mybatisplus.core.injector.AbstractMethod) GlobalConfig(com.baomidou.mybatisplus.core.config.GlobalConfig) MapperScan(org.mybatis.spring.annotation.MapperScan) Configuration(org.springframework.context.annotation.Configuration) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) MybatisConfiguration(com.baomidou.mybatisplus.core.MybatisConfiguration) MybatisSqlSessionFactoryBean(com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean) MybatisPlusInterceptor(com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor) List(java.util.List) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) MybatisMapWrapperFactory(com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory) SqlSessionFactory(org.apache.ibatis.session.SqlSessionFactory) DataSource(javax.sql.DataSource) FieldFill(com.baomidou.mybatisplus.annotation.FieldFill) AlwaysUpdateSomeColumnById(com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById) JdbcType(org.apache.ibatis.type.JdbcType) Bean(org.springframework.context.annotation.Bean) DefaultSqlInjector(com.baomidou.mybatisplus.core.injector.DefaultSqlInjector) PaginationInnerInterceptor(com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor) GlobalConfig(com.baomidou.mybatisplus.core.config.GlobalConfig) AbstractMethod(com.baomidou.mybatisplus.core.injector.AbstractMethod) DefaultSqlInjector(com.baomidou.mybatisplus.core.injector.DefaultSqlInjector) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) InsertBatchSomeColumn(com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn) AlwaysUpdateSomeColumnById(com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById) MybatisSqlSessionFactoryBean(com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean) Bean(org.springframework.context.annotation.Bean)

Example 22 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project atjob by 1-2-3.

the class MybatisUtil method getOrderItemList.

/**
 * 生成用于 Mybatis plus 排序的 OrderItem 列表.
 *
 * @param sort 排序字符串,格式类似:userName.ascend-userAgd.decend
 * @param clazz 要进行排序的实体类型
 * @param isAppendPkOrder 是否追加主键作为第二排序字段。当使用分页排序时,如果第一排序字段有大量相同值,不追加一个唯一字段作为第二排序字段将导致分页数据混乱。
 * @return
 */
public static List<OrderItem> getOrderItemList(String sort, Class<?> clazz, Boolean isAppendPkOrder) {
    // 属性名 -> 字段名 映射
    TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
    Map<String, String> fieldsMap = tableInfo.getFieldList().stream().collect(Collectors.toMap(fieldInfo -> fieldInfo.getProperty(), fieldInfo -> fieldInfo.getColumn()));
    List<OrderItem> result = new ArrayList<OrderItem>();
    if (StringUtils.isNotBlank(sort)) {
        result = Stream.of(sort.split("-")).map(t -> {
            var sortSpec = t.split("[.]");
            var propName = sortSpec[0];
            var direction = sortSpec[1];
            return StringUtils.equals(direction, "ascend") ? OrderItem.asc(fieldsMap.get(propName)) : OrderItem.desc(fieldsMap.get(propName));
        }).collect(Collectors.toList());
    }
    if (isAppendPkOrder) {
        result.add(OrderItem.asc(tableInfo.getKeyColumn()));
    }
    return result;
}
Also used : DefaultIdentifierGenerator(com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator) OrderItem(com.baomidou.mybatisplus.core.metadata.OrderItem) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) TableInfoHelper(com.baomidou.mybatisplus.core.metadata.TableInfoHelper) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) List(java.util.List) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) Stream(java.util.stream.Stream) IdentifierGenerator(com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator) Map(java.util.Map) OrderItem(com.baomidou.mybatisplus.core.metadata.OrderItem) ArrayList(java.util.ArrayList) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo)

Example 23 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project citrus by Yiuman.

the class BasePreOrderTreeService method treeQuery.

@Override
public E treeQuery(Query query) {
    if (Objects.isNull(query)) {
        return load(false);
    }
    // 查询符合条件的列表
    List<E> list = list(query);
    if (CollectionUtils.isEmpty(list)) {
        return null;
    }
    // 找到列表ID
    List<K> ids = list.parallelStream().map(Tree::getId).collect(Collectors.toList());
    TableInfo table = SqlHelper.table(getEntityType());
    // 将查询到的列表的项的所有父节点查出来
    String parentSql = "t1.leftValue > t2. leftValue and t1.rightValue < t2.rightValue".replaceAll("leftValue", getLeftField()).replaceAll("rightValue", getRightField());
    list.addAll(getTreeMapper().treeLink(table.getTableName(), Wrappers.<E>query().apply(parentSql).in("t1." + table.getKeyColumn(), ids)));
    final E root = getRoot();
    // 传list进去前需要去重,并排除根节点
    initTreeFromList(root, list.parallelStream().distinct().filter(item -> !Objects.equals(item.getId(), root.getId())).collect(Collectors.toList()));
    return root;
}
Also used : TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo)

Example 24 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project platform by elveahuang.

the class AbstractEntityService method saveBatch.

/**
 * @see EntityService#saveBatch(Collection, int)
 */
@Override
public void saveBatch(Collection<T> entityList, int batchSize) {
    TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
    Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
    String keyProperty = tableInfo.getKeyProperty();
    Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
    SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, this.logger, entityList, batchSize, (sqlSession, entity) -> {
        Object idVal = tableInfo.getPropertyValue(entity, keyProperty);
        return StringUtils.checkValNull(idVal) || com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity));
    }, (sqlSession, entity) -> {
        MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
        param.put(Constants.ENTITY, entity);
        sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);
    });
}
Also used : MapperMethod(org.apache.ibatis.binding.MapperMethod) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo)

Example 25 with TableInfo

use of com.baomidou.mybatisplus.core.metadata.TableInfo in project lamp-util by zuihou.

the class SuperCacheServiceImpl method saveOrUpdateBatch.

@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
    TableInfo tableInfo = TableInfoHelper.getTableInfo(getEntityClass());
    Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
    String keyProperty = tableInfo.getKeyProperty();
    Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
    BiPredicate<SqlSession, T> predicate = (sqlSession, entity) -> {
        Object idVal = ReflectionKit.getFieldValue(entity, keyProperty);
        return StringUtils.checkValNull(idVal) || CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity));
    };
    BiConsumer<SqlSession, T> consumer = (sqlSession, entity) -> {
        MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
        param.put(Constants.ENTITY, entity);
        sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);
        // 清理缓存
        delCache(entity);
    };
    String sqlStatement = SqlHelper.getSqlStatement(this.mapperClass, SqlMethod.INSERT_ONE);
    return SqlHelper.executeBatch(getEntityClass(), log, entityList, batchSize, (sqlSession, entity) -> {
        if (predicate.test(sqlSession, entity)) {
            sqlSession.insert(sqlStatement, entity);
            // 设置缓存
            setCache(entity);
        } else {
            consumer.accept(sqlSession, entity);
        }
    });
}
Also used : SuperMapper(top.tangyh.basic.base.mapper.SuperMapper) Arrays(java.util.Arrays) ReflectionKit(com.baomidou.mybatisplus.core.toolkit.ReflectionKit) Autowired(org.springframework.beans.factory.annotation.Autowired) Constants(com.baomidou.mybatisplus.core.toolkit.Constants) Function(java.util.function.Function) ArrayList(java.util.ArrayList) StringUtils(com.baomidou.mybatisplus.core.toolkit.StringUtils) BiPredicate(java.util.function.BiPredicate) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) Lists(com.google.common.collect.Lists) CacheKeyBuilder(top.tangyh.basic.model.cache.CacheKeyBuilder) CollectionUtils(com.baomidou.mybatisplus.core.toolkit.CollectionUtils) BiConsumer(java.util.function.BiConsumer) SuperEntity(top.tangyh.basic.base.entity.SuperEntity) SqlSession(org.apache.ibatis.session.SqlSession) SqlMethod(com.baomidou.mybatisplus.core.enums.SqlMethod) Collection(java.util.Collection) SqlHelper(com.baomidou.mybatisplus.extension.toolkit.SqlHelper) Set(java.util.Set) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Serializable(java.io.Serializable) TableInfoHelper(com.baomidou.mybatisplus.core.metadata.TableInfoHelper) CollUtil(cn.hutool.core.collection.CollUtil) List(java.util.List) CacheOps(top.tangyh.basic.cache.repository.CacheOps) Assert(com.baomidou.mybatisplus.core.toolkit.Assert) ReflectUtil(cn.hutool.core.util.ReflectUtil) Convert(cn.hutool.core.convert.Convert) NonNull(org.springframework.lang.NonNull) CacheKey(top.tangyh.basic.model.cache.CacheKey) MapperMethod(org.apache.ibatis.binding.MapperMethod) Collections(java.util.Collections) Transactional(org.springframework.transaction.annotation.Transactional) MapperMethod(org.apache.ibatis.binding.MapperMethod) SqlSession(org.apache.ibatis.session.SqlSession) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

TableInfo (com.baomidou.mybatisplus.core.metadata.TableInfo)53 MapperMethod (org.apache.ibatis.binding.MapperMethod)14 Transactional (org.springframework.transaction.annotation.Transactional)13 List (java.util.List)11 Serializable (java.io.Serializable)9 Field (java.lang.reflect.Field)8 TableInfoHelper (com.baomidou.mybatisplus.core.metadata.TableInfoHelper)7 AbstractMethod (com.baomidou.mybatisplus.core.injector.AbstractMethod)6 SqlMethod (com.baomidou.mybatisplus.core.enums.SqlMethod)5 InsertBatchSomeColumn (com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn)5 Collection (java.util.Collection)5 TableFieldInfo (com.baomidou.mybatisplus.core.metadata.TableFieldInfo)4 Constants (com.baomidou.mybatisplus.core.toolkit.Constants)4 ArrayList (java.util.ArrayList)4 Collectors (java.util.stream.Collectors)4 SqlSession (org.apache.ibatis.session.SqlSession)4 CollUtil (cn.hutool.core.collection.CollUtil)3 Convert (cn.hutool.core.convert.Convert)3 ReflectUtil (cn.hutool.core.util.ReflectUtil)3 FieldFill (com.baomidou.mybatisplus.annotation.FieldFill)3