Search in sources :

Example 1 with EntityInfoCache

use of com.diboot.core.binding.parser.EntityInfoCache in project diboot by dibo-software.

the class BindingCacheManager method initEntityInfoCache.

/**
 * 初始化
 */
private static void initEntityInfoCache() {
    StaticMemoryCacheManager cacheManager = getCacheManager();
    if (cacheManager.isUninitializedCache(CACHE_NAME_CLASS_ENTITY) == false) {
        return;
    }
    // 初始化有service的entity缓存
    Map<String, IService> serviceMap = ContextHelper.getApplicationContext().getBeansOfType(IService.class);
    Set<String> uniqueEntitySet = new HashSet<>();
    if (V.notEmpty(serviceMap)) {
        for (Map.Entry<String, IService> entry : serviceMap.entrySet()) {
            Class entityClass = BeanUtils.getGenericityClass(entry.getValue(), 1);
            if (entityClass != null) {
                IService entityIService = entry.getValue();
                if (uniqueEntitySet.contains(entityClass.getName())) {
                    if (entityIService.getClass().getAnnotation(Primary.class) != null) {
                        EntityInfoCache entityInfoCache = cacheManager.getCacheObj(CACHE_NAME_CLASS_ENTITY, entityClass.getName(), EntityInfoCache.class);
                        if (entityInfoCache != null) {
                            entityInfoCache.setService(entityIService);
                        }
                    } else {
                        log.warn("Entity: {} 存在多个service实现类,可能导致调用实例与预期不一致!", entityClass.getName());
                    }
                } else {
                    EntityInfoCache entityInfoCache = new EntityInfoCache(entityClass, entityIService);
                    cacheManager.putCacheObj(CACHE_NAME_CLASS_ENTITY, entityClass.getName(), entityInfoCache);
                    cacheManager.putCacheObj(CACHE_NAME_TABLE_ENTITY, entityInfoCache.getTableName(), entityInfoCache);
                    cacheManager.putCacheObj(CACHE_NAME_ENTITYNAME_CLASS, entityClass.getSimpleName(), entityClass);
                    uniqueEntitySet.add(entityClass.getName());
                }
            }
        }
    } else {
        log.debug("未获取到任何有效@Service.");
    }
    // 初始化没有service的table-mapper缓存
    SqlSessionFactory sqlSessionFactory = ContextHelper.getBean(SqlSessionFactory.class);
    Collection<Class<?>> mappers = sqlSessionFactory.getConfiguration().getMapperRegistry().getMappers();
    if (V.notEmpty(mappers)) {
        for (Class<?> mapperClass : mappers) {
            Type[] types = mapperClass.getGenericInterfaces();
            try {
                if (types != null && types.length > 0 && types[0] != null) {
                    ParameterizedType genericType = (ParameterizedType) types[0];
                    Type[] superTypes = genericType.getActualTypeArguments();
                    if (superTypes != null && superTypes.length > 0 && superTypes[0] != null) {
                        String entityClassName = superTypes[0].getTypeName();
                        if (!uniqueEntitySet.contains(entityClassName) && entityClassName.length() > 1) {
                            Class<?> entityClass = Class.forName(entityClassName);
                            BaseMapper mapper = (BaseMapper) ContextHelper.getBean(mapperClass);
                            EntityInfoCache entityInfoCache = new EntityInfoCache(entityClass, null);
                            entityInfoCache.setBaseMapper(mapper);
                            cacheManager.putCacheObj(CACHE_NAME_CLASS_ENTITY, entityClass.getName(), entityInfoCache);
                            cacheManager.putCacheObj(CACHE_NAME_TABLE_ENTITY, entityInfoCache.getTableName(), entityInfoCache);
                            cacheManager.putCacheObj(CACHE_NAME_ENTITYNAME_CLASS, entityClass.getSimpleName(), entityClass);
                            uniqueEntitySet.add(entityClass.getName());
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("解析mapper异常", e);
            }
        }
    }
    uniqueEntitySet = null;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Primary(org.springframework.context.annotation.Primary) StaticMemoryCacheManager(com.diboot.core.cache.StaticMemoryCacheManager) SqlSessionFactory(org.apache.ibatis.session.SqlSessionFactory) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) EntityInfoCache(com.diboot.core.binding.parser.EntityInfoCache) IService(com.baomidou.mybatisplus.extension.service.IService)

Example 2 with EntityInfoCache

use of com.diboot.core.binding.parser.EntityInfoCache in project diboot by dibo-software.

the class BaseServiceTest method testCache.

@Test
public void testCache() {
    EntityInfoCache entityInfoCache = BindingCacheManager.getEntityInfoByClass(Dictionary.class);
    Assert.assertTrue(entityInfoCache != null);
    Assert.assertTrue(entityInfoCache.getDeletedColumn().equals("is_deleted"));
    entityInfoCache = BindingCacheManager.getEntityInfoByClass(CcCityInfo.class);
    Assert.assertTrue(entityInfoCache != null);
    Assert.assertTrue(entityInfoCache.getIdColumn().equals("id"));
    Assert.assertTrue(entityInfoCache.getDeletedColumn() == null);
    BaseMapper baseMapper = BindingCacheManager.getMapperByTable("user_role");
    Assert.assertTrue(baseMapper != null);
    Class<?> entityClass = BindingCacheManager.getEntityClassBySimpleName("Dictionary");
    Assert.assertTrue(entityClass != null && entityClass.getName().equals(Dictionary.class.getName()));
    // 测试PropInfo缓存
    QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("type", "GENDER").eq("item_value", "F");
    Dictionary dictionary = dictionaryService.getSingleEntity(queryWrapper);
    DictionaryVO dictionaryVO = RelationsBinder.convertAndBind(dictionary, DictionaryVO.class);
    Assert.assertTrue(dictionaryVO.getPrimaryKeyVal().equals(dictionary.getId()));
    Assert.assertTrue(ContextHelper.getIdFieldName(dictionaryVO.getClass()).equals("id"));
}
Also used : Dictionary(com.diboot.core.entity.Dictionary) CcCityInfo(diboot.core.test.binder.entity.CcCityInfo) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) SimpleDictionaryVO(diboot.core.test.binder.vo.SimpleDictionaryVO) EntityInfoCache(com.diboot.core.binding.parser.EntityInfoCache) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 3 with EntityInfoCache

use of com.diboot.core.binding.parser.EntityInfoCache in project diboot by dibo-software.

the class BaseServiceImpl method cancelDeletedById.

@Override
public boolean cancelDeletedById(Serializable id) {
    EntityInfoCache info = BindingCacheManager.getEntityInfoByClass(super.getEntityClass());
    String tableName = info.getTableName();
    return this.getMapper().cancelDeletedById(tableName, id) > 0;
}
Also used : EntityInfoCache(com.diboot.core.binding.parser.EntityInfoCache)

Example 4 with EntityInfoCache

use of com.diboot.core.binding.parser.EntityInfoCache in project diboot by dibo-software.

the class BaseServiceImpl method getId2NameMap.

@Override
public <ID> Map<ID, String> getId2NameMap(List<ID> entityIds, IGetter<T> getterFn) {
    if (V.isEmpty(entityIds)) {
        return Collections.emptyMap();
    }
    String fieldName = BeanUtils.convertToFieldName(getterFn);
    EntityInfoCache entityInfo = BindingCacheManager.getEntityInfoByClass(this.getEntityClass());
    String columnName = entityInfo.getColumnByField(fieldName);
    QueryWrapper<T> queryWrapper = new QueryWrapper<T>().select(entityInfo.getIdColumn(), columnName).in(entityInfo.getIdColumn(), entityIds);
    // map列表
    List<Map<String, Object>> mapList = getMapList(queryWrapper);
    if (V.isEmpty(mapList)) {
        return Collections.emptyMap();
    }
    Map<ID, String> idNameMap = new HashMap<>(mapList.size());
    for (Map<String, Object> map : mapList) {
        ID key = (ID) map.get(entityInfo.getIdColumn());
        String value = S.valueOf(map.get(columnName));
        idNameMap.put(key, value);
    }
    return idNameMap;
}
Also used : LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) DynamicJoinQueryWrapper(com.diboot.core.binding.query.dynamic.DynamicJoinQueryWrapper) EntityInfoCache(com.diboot.core.binding.parser.EntityInfoCache)

Example 5 with EntityInfoCache

use of com.diboot.core.binding.parser.EntityInfoCache in project diboot by dibo-software.

the class BaseServiceImpl method createOrUpdateN2NRelations.

@Override
@Transactional(rollbackFor = Exception.class)
public <R> boolean createOrUpdateN2NRelations(SFunction<R, ?> driverIdGetter, Object driverId, SFunction<R, ?> followerIdGetter, List<? extends Serializable> followerIdList, Consumer<QueryWrapper<R>> queryConsumer, Consumer<R> setConsumer) {
    if (driverId == null) {
        throw new InvalidUsageException("主动ID值不能为空!");
    }
    if (followerIdList == null) {
        log.debug("从动对象ID集合为null,不做关联关系更新处理");
        return false;
    }
    // 从getter中获取class和fieldName
    LambdaMeta lambdaMeta = LambdaUtils.extract(driverIdGetter);
    Class<R> middleTableClass = (Class<R>) lambdaMeta.getInstantiatedClass();
    EntityInfoCache entityInfo = BindingCacheManager.getEntityInfoByClass(middleTableClass);
    if (entityInfo == null) {
        throw new InvalidUsageException("未找到 " + middleTableClass.getName() + " 的 Service 或 Mapper 定义!");
    }
    boolean isExistPk = entityInfo.getIdColumn() != null;
    // 获取主动从动字段名
    String driverFieldName = PropertyNamer.methodToProperty(lambdaMeta.getImplMethodName());
    String followerFieldName = convertGetterToFieldName(followerIdGetter);
    String driverColumnName = entityInfo.getColumnByField(driverFieldName);
    String followerColumnName = entityInfo.getColumnByField(followerFieldName);
    // 查询已有关联
    QueryWrapper<R> selectOld = new QueryWrapper<R>().eq(driverColumnName, driverId);
    if (queryConsumer != null) {
        queryConsumer.accept(selectOld);
    }
    if (isExistPk) {
        selectOld.select(entityInfo.getIdColumn(), followerColumnName);
    } else {
        selectOld.select(followerColumnName);
    }
    List<Map<String, Object>> oldMap;
    IService<R> iService = entityInfo.getService();
    BaseMapper<R> baseMapper = entityInfo.getBaseMapper();
    if (iService != null) {
        oldMap = iService.listMaps(selectOld);
    } else {
        oldMap = baseMapper.selectMaps(selectOld);
    }
    // 删除失效关联
    List<Serializable> delIds = new ArrayList<>();
    for (Map<String, Object> map : oldMap) {
        if (V.notEmpty(followerIdList) && followerIdList.remove((Serializable) map.get(followerColumnName))) {
            continue;
        }
        delIds.add((Serializable) map.get(isExistPk ? entityInfo.getIdColumn() : followerColumnName));
    }
    if (!delIds.isEmpty()) {
        if (isExistPk) {
            if (iService != null) {
                iService.removeByIds(delIds);
            } else {
                baseMapper.deleteBatchIds(delIds);
            }
        } else {
            QueryWrapper<R> delOld = new QueryWrapper<R>().eq(driverColumnName, driverId).in(entityInfo.getColumnByField(followerFieldName), delIds);
            if (queryConsumer != null) {
                queryConsumer.accept(selectOld);
            }
            if (iService != null) {
                iService.remove(delOld);
            } else if (!delIds.isEmpty()) {
                baseMapper.delete(delOld);
            }
        }
    }
    // 新增关联
    if (V.notEmpty(followerIdList)) {
        List<R> n2nRelations = new ArrayList<>(followerIdList.size());
        try {
            for (Serializable followerId : followerIdList) {
                R relation = middleTableClass.newInstance();
                BeanUtils.setProperty(relation, driverFieldName, driverId);
                BeanUtils.setProperty(relation, followerFieldName, followerId);
                if (setConsumer != null) {
                    setConsumer.accept(relation);
                }
                n2nRelations.add(relation);
            }
        } catch (Exception e) {
            throw new BusinessException(Status.FAIL_EXCEPTION, e);
        }
        if (iService != null) {
            if (iService instanceof BaseService) {
                ((BaseService<R>) iService).createEntities(n2nRelations);
            } else {
                iService.saveBatch(n2nRelations);
            }
        } else {
            // 新增关联,无service只能循环插入
            for (R relation : n2nRelations) {
                baseMapper.insert(relation);
            }
        }
    }
    return true;
}
Also used : Serializable(java.io.Serializable) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) DynamicJoinQueryWrapper(com.diboot.core.binding.query.dynamic.DynamicJoinQueryWrapper) InvalidUsageException(com.diboot.core.exception.InvalidUsageException) BusinessException(com.diboot.core.exception.BusinessException) LambdaMeta(com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta) BusinessException(com.diboot.core.exception.BusinessException) EntityInfoCache(com.diboot.core.binding.parser.EntityInfoCache) BaseService(com.diboot.core.service.BaseService) InvalidUsageException(com.diboot.core.exception.InvalidUsageException) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

EntityInfoCache (com.diboot.core.binding.parser.EntityInfoCache)8 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)3 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)3 IService (com.baomidou.mybatisplus.extension.service.IService)3 BaseMapper (com.baomidou.mybatisplus.core.mapper.BaseMapper)2 DynamicJoinQueryWrapper (com.diboot.core.binding.query.dynamic.DynamicJoinQueryWrapper)2 BaseService (com.diboot.core.service.BaseService)2 LambdaMeta (com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta)1 StaticMemoryCacheManager (com.diboot.core.cache.StaticMemoryCacheManager)1 Dictionary (com.diboot.core.entity.Dictionary)1 BusinessException (com.diboot.core.exception.BusinessException)1 InvalidUsageException (com.diboot.core.exception.InvalidUsageException)1 CcCityInfo (diboot.core.test.binder.entity.CcCityInfo)1 SimpleDictionaryVO (diboot.core.test.binder.vo.SimpleDictionaryVO)1 Serializable (java.io.Serializable)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 SqlSessionFactory (org.apache.ibatis.session.SqlSessionFactory)1 Test (org.junit.Test)1 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)1