Search in sources :

Example 16 with MapperMetadata

use of com.mendmix.mybatis.metadata.MapperMetadata in project jeesuite-libs by vakinge.

the class CacheHandler method onFinished.

@SuppressWarnings("rawtypes")
@Override
public void onFinished(InvocationVals invocationVal, Object result) {
    try {
        if (BLOCK_ON_CONCURRENT_LOCK_RETURN.equals(result))
            return;
        MappedStatement mt = invocationVal.getMappedStatement();
        QueryCacheMethodMetadata metadata = null;
        if (mt.getSqlCommandType().equals(SqlCommandType.SELECT)) {
            if (result == null)
                return;
            if ((metadata = invocationVal.getQueryMethodMetadata()) == null)
                return;
            final String cacheKey = invocationVal.getCacheKey();
            if (result instanceof List) {
                List list = (List) result;
                if (list.isEmpty()) {
                    if (nullValueCache) {
                        CacheUtils.set(cacheKey, NULL_PLACEHOLDER, IN_1MINS);
                    }
                    return;
                }
                result = metadata.collectionResult ? result : list.get(0);
            }
            // 
            if (!metadata.isSecondQueryById()) {
                CacheUtils.set(cacheKey, result, metadata.getExpire());
                if (logger.isDebugEnabled())
                    logger.debug(">>auto_cache_process addCache -> mapperId:{},cacheKey:{}", mt.getId(), cacheKey);
                if (metadata.isPk) {
                    // 唯一索引(业务上)
                    cacheUniqueSelectRef(invocationVal, result, mt, cacheKey);
                } else if (metadata.groupRalated) {
                    // 结果为集合的情况,增加key到cacheGroup
                    CacheUtils.addListItems(metadata.cacheGroupKey, cacheKey);
                }
            } else {
                // 之前没有按主键的缓存,增加按主键缓存
                String idCacheKey = genarateQueryCacheKey(invocationVal, getQueryByPkMethodCache(mt.getId()).keyPattern, result);
                if (idCacheKey != null && cacheKey != null) {
                    if (!CacheUtils.exists(idCacheKey)) {
                        // 缓存idkey->实体
                        CacheUtils.set(idCacheKey, result, metadata.getExpire());
                    }
                    // 缓存fieldkey->idkey
                    cacheFieldRefKey(cacheKey, idCacheKey, metadata.getExpire());
                    if (logger.isDebugEnabled())
                        logger.debug(">>auto_cache_process addCache -> mapperId:{},idCacheKey:{},cacheKey:{}", mt.getId(), idCacheKey, cacheKey);
                }
            }
        } else {
            String mapperClassName = invocationVal.getMapperNameSpace();
            if (!cacheEnableMappers.contains(mapperClassName) && !customUpdateCacheMapppings.containsKey(mt.getId()))
                return;
            // 返回0,未更新成功
            if (result != null && ((int) result) == 0)
                return;
            // 更新方法移除缓存,避免事务回滚导致缓存不一致,所以更新方法直接移除缓存
            if (mt.getSqlCommandType().equals(SqlCommandType.INSERT)) {
            // TODO 写入缓存 ,考虑回滚
            } else {
                if (updatePkCacheMethods.containsKey(mt.getId())) {
                    UpdateByPkCacheMethodMetadata updateMethodCache = updatePkCacheMethods.get(mt.getId());
                    String idCacheKey = genarateQueryCacheKey(invocationVal, updateMethodCache.keyPattern, invocationVal.getParameter());
                    CacheUtils.remove(idCacheKey);
                } else {
                    // 针对按条件更新或者删除的方法,按查询条件查询相关内容,然后清理对应主键缓存内容
                    MapperMetadata mapperMeta = MybatisMapperParser.getMapperMetadata(mapperClassName);
                    final Object parameter = invocationVal.getArgs()[1];
                    BoundSql boundSql = mt.getBoundSql(parameter);
                    String orignSql = boundSql.getSql();
                    ColumnMetadata idColumn = mapperMeta.getEntityMetadata().getIdColumn();
                    SqlMetadata sqlMetadata = MybatisSqlUtils.rewriteAsSelectPkField(orignSql, idColumn.getColumn());
                    // 
                    String tenantId = CurrentRuntimeContext.getTenantId();
                    cleanCacheExecutor.execute(new Runnable() {

                        @Override
                        public void run() {
                            if (tenantId != null) {
                                CurrentRuntimeContext.setTenantId(tenantId);
                            }
                            removeCacheByDyncQuery(mapperMeta, boundSql, sqlMetadata);
                        }
                    });
                }
            }
            // 删除同一cachegroup关联缓存
            removeCacheByGroup(mt.getId(), mapperClassName);
            // 删除自定义关联缓存
            if (customUpdateCacheMapppings.containsKey(mt.getId())) {
                removeCustomRelateCache(mt.getId());
            }
        }
    } finally {
        // 清除并发控制锁
        if (invocationVal.getConcurrentLockKey() != null) {
            CacheUtils.remove(invocationVal.getConcurrentLockKey());
        }
    }
}
Also used : ColumnMetadata(com.mendmix.mybatis.metadata.ColumnMetadata) BoundSql(org.apache.ibatis.mapping.BoundSql) List(java.util.List) ArrayList(java.util.ArrayList) SqlMetadata(com.mendmix.mybatis.metadata.SqlMetadata) MappedStatement(org.apache.ibatis.mapping.MappedStatement) MapperMetadata(com.mendmix.mybatis.metadata.MapperMetadata)

Example 17 with MapperMetadata

use of com.mendmix.mybatis.metadata.MapperMetadata in project jeesuite-libs by vakinge.

the class PaginationHandler method start.

@Override
public void start(JeesuiteMybatisInterceptor context) {
    this.dbType = DatabaseType.valueOf(MybatisConfigs.getDbType(context.getGroupName()));
    logger.info("dbType:{}", dbType.name());
    List<MapperMetadata> mappers = MybatisMapperParser.getMapperMetadatas(context.getGroupName());
    for (MapperMetadata e : mappers) {
        Class<?> mapperClass = e.getMapperClass();
        Method[] methods = mapperClass.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getReturnType() == Page.class) {
                String msId = e.getMapperClass().getName() + "." + method.getName();
                boolean withPageParams = false;
                Class<?>[] parameterTypes = method.getParameterTypes();
                self: for (Class<?> clazz : parameterTypes) {
                    if (withPageParams = (clazz == PageParams.class || clazz.getSuperclass() == PageParams.class)) {
                        break self;
                    }
                }
                if (!withPageParams) {
                    throw new MybatisHanlerInitException(String.format("method[%s] returnType is:Page,but not found Parameter[PageParams] in Parameters list", method.getName()));
                }
                pageMappedStatements.put(msId, true);
            }
        }
    }
}
Also used : Method(java.lang.reflect.Method) MapperMetadata(com.mendmix.mybatis.metadata.MapperMetadata) MybatisHanlerInitException(com.mendmix.mybatis.exception.MybatisHanlerInitException)

Example 18 with MapperMetadata

use of com.mendmix.mybatis.metadata.MapperMetadata in project jeesuite-libs by vakinge.

the class GeneralSqlGenerator method generate.

public void generate() {
    if (languageDriver == null)
        languageDriver = configuration.getDefaultScriptingLanguageInstance();
    List<MapperMetadata> mappers = MybatisMapperParser.getMapperMetadatas(group);
    for (MapperMetadata entity : mappers) {
        entity.setGroup(group);
        new InsertBuilder().build(configuration, languageDriver, entity);
        new InsertListBuilder().build(configuration, languageDriver, entity);
        new DeleteByPrimaryKeyBuilder().build(configuration, languageDriver, entity);
        new UpdateBuilder().build(configuration, languageDriver, entity);
        new SelectAllBuilder().build(configuration, languageDriver, entity);
        new SelectByPrimaryKeyBuilder().build(configuration, languageDriver, entity);
        new SelectByPrimaryKeysBuilder().build(configuration, languageDriver, entity);
        new CountAllBuilder().build(configuration, languageDriver, entity);
        log.info(" >> generate autoCrud for:[{}] finish", entity.getEntityClass().getName());
    }
}
Also used : InsertBuilder(com.mendmix.mybatis.crud.builder.InsertBuilder) SelectAllBuilder(com.mendmix.mybatis.crud.builder.SelectAllBuilder) DeleteByPrimaryKeyBuilder(com.mendmix.mybatis.crud.builder.DeleteByPrimaryKeyBuilder) CountAllBuilder(com.mendmix.mybatis.crud.builder.CountAllBuilder) InsertListBuilder(com.mendmix.mybatis.crud.builder.InsertListBuilder) SelectByPrimaryKeyBuilder(com.mendmix.mybatis.crud.builder.SelectByPrimaryKeyBuilder) SelectByPrimaryKeysBuilder(com.mendmix.mybatis.crud.builder.SelectByPrimaryKeysBuilder) UpdateBuilder(com.mendmix.mybatis.crud.builder.UpdateBuilder) MapperMetadata(com.mendmix.mybatis.metadata.MapperMetadata)

Aggregations

MapperMetadata (com.mendmix.mybatis.metadata.MapperMetadata)18 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)6 MappedStatement (org.apache.ibatis.mapping.MappedStatement)6 List (java.util.List)5 ColumnMetadata (com.mendmix.mybatis.metadata.ColumnMetadata)4 JeesuiteMybatisInterceptor (com.mendmix.mybatis.plugin.JeesuiteMybatisInterceptor)4 Map (java.util.Map)4 BoundSql (org.apache.ibatis.mapping.BoundSql)4 CurrentRuntimeContext (com.mendmix.common.CurrentRuntimeContext)3 AuthUser (com.mendmix.common.model.AuthUser)3 OrderBy (com.mendmix.common.model.OrderBy)3 PageParams (com.mendmix.common.model.PageParams)3 ResourceUtils (com.mendmix.common.util.ResourceUtils)3 MybatisConfigs (com.mendmix.mybatis.MybatisConfigs)3 MybatisRuntimeContext (com.mendmix.mybatis.MybatisRuntimeContext)3 InterceptorHandler (com.mendmix.mybatis.core.InterceptorHandler)3 CrudMethods (com.mendmix.mybatis.crud.CrudMethods)3 MybatisSqlUtils (com.mendmix.mybatis.kit.MybatisSqlUtils)3 MapperMethod (com.mendmix.mybatis.metadata.MapperMetadata.MapperMethod)3