Search in sources :

Example 1 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper 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 BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper 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 BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper in project diboot by dibo-software.

the class MiddleTable method queryByMapper.

/**
 * 通过定义的Mapper查询结果
 * @param linkage
 * @param trunkObjCol2ValuesMap
 * @return
 */
private List<Map<String, Object>> queryByMapper(EntityInfoCache linkage, Map<String, List> trunkObjCol2ValuesMap) {
    QueryWrapper queryWrapper = new QueryWrapper<>();
    queryWrapper.setEntityClass(linkage.getEntityClass());
    // select所需字段
    queryWrapper.select(getSelectColumns());
    for (Map.Entry<String, List> entry : trunkObjCol2ValuesMap.entrySet()) {
        String column = entry.getKey();
        if (column != null && V.notEmpty(entry.getValue())) {
            queryWrapper.in(column, entry.getValue());
        }
    }
    if (additionalConditions != null) {
        for (String condition : additionalConditions) {
            queryWrapper.apply(condition);
        }
    }
    BaseMapper mapper = linkage.getBaseMapper();
    List<Map<String, Object>> resultSetMapList = mapper.selectMaps(queryWrapper);
    return resultSetMapList;
}
Also used : QueryWrapper(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper)

Example 4 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper in project diboot by dibo-software.

the class BaseServiceImpl method createEntityAndRelatedEntities.

@Override
@Transactional(rollbackFor = Exception.class)
public <RE, R> boolean createEntityAndRelatedEntities(T entity, List<RE> relatedEntities, ISetter<RE, R> relatedEntitySetter) {
    boolean success = createEntity(entity);
    if (!success) {
        log.warn("新建Entity失败: {}", entity.toString());
        return false;
    }
    if (V.isEmpty(relatedEntities)) {
        return true;
    }
    Class relatedEntityClass = relatedEntities.get(0).getClass();
    // 获取主键
    Object pkValue = getPrimaryKeyValue(entity);
    String attributeName = BeanUtils.convertToFieldName(relatedEntitySetter);
    // 填充关联关系
    relatedEntities.forEach(relatedEntity -> BeanUtils.setProperty(relatedEntity, attributeName, pkValue));
    // 获取关联对象对应的Service
    BaseService relatedEntityService = ContextHelper.getBaseServiceByEntity(relatedEntityClass);
    if (relatedEntityService != null) {
        return relatedEntityService.createEntities(relatedEntities);
    } else {
        // 查找mapper
        BaseMapper mapper = ContextHelper.getBaseMapperByEntity(entity.getClass());
        // 新增关联,无service只能循环插入
        for (RE relation : relatedEntities) {
            mapper.insert(relation);
        }
        return true;
    }
}
Also used : BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) BaseService(com.diboot.core.service.BaseService) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper in project solon by noear.

the class SqlHelper method getMapper.

/**
 * 通过entityClass获取Mapper,记得要释放连接
 * 例: {@code
 * SqlSession sqlSession = SqlHelper.sqlSession(entityClass);
 * try {
 *     BaseMapper<User> userMapper = getMapper(User.class, sqlSession);
 * } finally {
 *     sqlSession.close();
 * }
 * }
 *
 * @param entityClass 实体
 * @param <T>         实体类型
 * @return Mapper
 */
@SuppressWarnings("unchecked")
public static <T> BaseMapper<T> getMapper(Class<T> entityClass, SqlSession sqlSession) {
    Optional.ofNullable(entityClass).orElseThrow(() -> ExceptionUtils.mpe("entityClass can't be null!"));
    TableInfo tableInfo = Optional.ofNullable(TableInfoHelper.getTableInfo(entityClass)).orElseThrow(() -> ExceptionUtils.mpe("Can not find TableInfo from Class: \"%s\".", entityClass.getName()));
    try {
        Configuration configuration = tableInfo.getConfiguration();
        return (BaseMapper<T>) configuration.getMapper(Class.forName(tableInfo.getCurrentNamespace()), sqlSession);
    } catch (ClassNotFoundException e) {
        throw ExceptionUtils.mpe(e);
    }
}
Also used : Configuration(org.apache.ibatis.session.Configuration) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo)

Aggregations

BaseMapper (com.baomidou.mybatisplus.core.mapper.BaseMapper)8 QueryWrapper (com.baomidou.mybatisplus.core.conditions.query.QueryWrapper)2 TableInfo (com.baomidou.mybatisplus.core.metadata.TableInfo)2 EntityInfoCache (com.diboot.core.binding.parser.EntityInfoCache)2 Test (org.junit.Test)2 CollectionUtil (cn.hutool.core.collection.CollectionUtil)1 ArrayUtil (cn.hutool.core.util.ArrayUtil)1 TypeUtil (cn.hutool.core.util.TypeUtil)1 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)1 TableInfoHelper (com.baomidou.mybatisplus.core.metadata.TableInfoHelper)1 IService (com.baomidou.mybatisplus.extension.service.IService)1 City (com.baomidou.mybatisplus.samples.reduce.springmvc.entity.City)1 User (com.baomidou.mybatisplus.samples.reduce.springmvc.entity.User)1 StaticMemoryCacheManager (com.diboot.core.cache.StaticMemoryCacheManager)1 Dictionary (com.diboot.core.entity.Dictionary)1 BaseService (com.diboot.core.service.BaseService)1 CrudMapper (com.github.yiuman.citrus.support.crud.mapper.CrudMapper)1 TreeMapper (com.github.yiuman.citrus.support.crud.mapper.TreeMapper)1 BaseService (com.github.yiuman.citrus.support.crud.service.BaseService)1 CrudService (com.github.yiuman.citrus.support.crud.service.CrudService)1