use of com.github.yiuman.citrus.support.crud.mapper.CrudMapper in project citrus by Yiuman.
the class CrudHelper method getMapper.
/**
* 根据实体以及基础Mapper接口获取Mapper
*
* @param entityClass 实体Class
* @param baseMapperClass 基础Mapper基础的Class
* @param <M> Mapper泛型
* @param <T> 实体泛型
* @return 从Mybatis取出的Mapper代理对象(可能为动态字节码Mapper)
*/
@SuppressWarnings("unchecked")
public static <M extends BaseMapper<T>, T> M getMapper(Class<T> entityClass, Class<?> baseMapperClass) {
try {
// 多线程的使用 线程安全的SqlSessionTemplate
SqlSessionTemplate sqlSessionTemplate = SpringUtils.getBean(SqlSessionTemplate.class);
// 先看下Mapper与实体映射的缓存是否为空,为空则初始化已注册的实体缓存信息
if (CollectionUtil.isEmpty(MAPPER_CACHE.keySet())) {
// 找到Mapper注册器
MapperRegistry mapperRegistry = sqlSessionTemplate.getConfiguration().getMapperRegistry();
mapperRegistry.getMappers().stream().filter(mapperInterface -> {
Class<?>[] interfaces = mapperInterface.getInterfaces();
// 找到是CrudMapper的实现
return ArrayUtil.isNotEmpty(interfaces) && interfaces[0].isAssignableFrom(CrudMapper.class);
}).forEach(baseMapperInterface -> MAPPER_CACHE.put((Class<?>) TypeUtil.getTypeArgument(baseMapperInterface, 0), (Class<? extends BaseMapper<?>>) baseMapperInterface));
}
Class<? extends BaseMapper<?>> mapperClass = MAPPER_CACHE.get(entityClass);
if (Objects.isNull(mapperClass)) {
mapperClass = CrudUtils.getMapperInterface(entityClass, baseMapperClass);
MAPPER_CACHE.put(entityClass, mapperClass);
}
M mapper;
synchronized (mapperClass) {
try {
mapper = (M) sqlSessionTemplate.getMapper(mapperClass);
} catch (BindingException e) {
sqlSessionTemplate.getConfiguration().addMapper(mapperClass);
mapper = (M) sqlSessionTemplate.getMapper(mapperClass);
}
}
return mapper;
} catch (Throwable throwable) {
log.error("Cannot auto get mapper for entity {} and mapperInterface {}", entityClass, baseMapperClass, throwable);
throw new RuntimeException(throwable);
}
}
Aggregations