Search in sources :

Example 6 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper in project study-by-myself by Howinfun.

the class LogRecordAspect method around.

@Around("@annotation(logRecordAnno))")
public Object around(ProceedingJoinPoint point, LogRecordAnno logRecordAnno) throws Throwable {
    Method method = this.getMethod(point);
    Object[] args = point.getArgs();
    // 日志记录
    LogRecord logRecord = new LogRecord();
    // 日志类型
    LogTypeEnum logType = logRecordAnno.logType();
    // 业务名称
    String businessName = logRecordAnno.businessName();
    EvaluationContext context = this.bindParam(method, args);
    // 获取操作者
    String operator = this.getOperator(logRecordAnno.operator(), context);
    logRecord.setLogType(logType);
    logRecord.setBusinessName(businessName);
    logRecord.setOperator(operator);
    Object proceedResult = null;
    // 记录实体记录
    if (LogTypeEnum.RECORD.equals(logType)) {
        SqlTypeEnum sqlType = logRecordAnno.sqlType();
        Class mapperClass = logRecordAnno.mapperName();
        if (mapperClass.isAssignableFrom(BaseMapper.class)) {
            throw new RuntimeException("mapperClass 属性传入 Class 不是 BaseMapper 的子类");
        }
        BaseMapper mapper = (BaseMapper) applicationContext.getBean(mapperClass);
        String id;
        Object beforeRecord;
        Object afterRecord;
        switch(sqlType) {
            // 新增
            case INSERT:
                logRecord.setSqlType(SqlTypeEnum.INSERT);
                proceedResult = point.proceed();
                // 根据spel表达式获取id
                id = (String) this.getId(logRecordAnno.id(), context);
                Object result = mapper.selectById(id);
                logRecord.setBeforeRecord("");
                logRecord.setAfterRecord(JSON.toJSONString(result));
                break;
            // 更新
            case UPDATE:
                logRecord.setSqlType(SqlTypeEnum.UPDATE);
                // 根据spel表达式获取id
                id = (String) this.getId(logRecordAnno.id(), context);
                beforeRecord = mapper.selectById(id);
                proceedResult = point.proceed();
                afterRecord = mapper.selectById(id);
                logRecord.setBeforeRecord(JSON.toJSONString(beforeRecord));
                logRecord.setAfterRecord(JSON.toJSONString(afterRecord));
                break;
            // 删除
            case DELETE:
                logRecord.setSqlType(SqlTypeEnum.DELETE);
                // 根据spel表达式获取id
                id = (String) this.getId(logRecordAnno.id(), context);
                beforeRecord = mapper.selectById(id);
                proceedResult = point.proceed();
                logRecord.setBeforeRecord(JSON.toJSONString(beforeRecord));
                logRecord.setAfterRecord("");
                break;
            default:
                break;
        }
    // 记录信息
    } else if (LogTypeEnum.MESSAGE.equals(logType)) {
        try {
            proceedResult = point.proceed();
            String successMsg = logRecordAnno.successMsg();
            // 对成功信息做表达式提取
            Matcher successMatcher = PATTERN.matcher(successMsg);
            while (successMatcher.find()) {
                String temp = successMatcher.group();
                Expression tempExpression = parser.parseExpression(temp);
                String result = (String) tempExpression.getValue(context);
                temp = "{{" + temp + "}}";
                successMsg = successMsg.replace(temp, result);
            }
            logRecord.setSuccessMsg(successMsg);
        } catch (Exception e) {
            String errorMsg = logRecordAnno.errorMsg();
            String exceptionMsg = e.getMessage();
            errorMsg = errorMsg.replace(LogRecordContants.ERROR_MSG_PATTERN, exceptionMsg);
            logRecord.setSuccessMsg(errorMsg);
            // 插入记录
            logRecord.setCreateTime(LocalDateTime.now());
            this.logRecordSDKService.insertLogRecord(logRecord);
            // 回抛异常
            throw new Exception(errorMsg);
        }
    }
    // 插入记录
    logRecord.setCreateTime(LocalDateTime.now());
    this.logRecordSDKService.insertLogRecord(logRecord);
    return proceedResult;
}
Also used : Matcher(java.util.regex.Matcher) Method(java.lang.reflect.Method) LogRecord(com.winfun.log.sdk.entity.LogRecord) Expression(org.springframework.expression.Expression) LogTypeEnum(com.winfun.log.sdk.entity.enums.LogTypeEnum) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) SqlTypeEnum(com.winfun.log.sdk.entity.enums.SqlTypeEnum) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Around(org.aspectj.lang.annotation.Around)

Example 7 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper in project mybatis-plus-samples by baomidou.

the class ReduceTest method testGeneratedMapper.

@Test
public void testGeneratedMapper() {
    String cityMapperClassName = "cityMapper";
    BaseMapper cityMapper = (BaseMapper) context.getBean(cityMapperClassName);
    City city = (City) cityMapper.selectById(1);
    Assertions.assertEquals(city.getId().longValue(), 1L);
    String districtMapperClassName = "districtMapper";
    boolean isContained = context.containsBean(districtMapperClassName);
    Assertions.assertFalse(isContained);
    // BaseMapper districtMapper =(BaseMapper) context.getBean(districtMapperClassName);
    // District district = (District) districtMapper.selectById(1);
    // Assertions.assertEquals(district.getId().longValue(),1L);
    String userMapperClassName = "userMapper";
    BaseMapper userMapper = (BaseMapper) context.getBean(userMapperClassName);
    userMapper.selectById(1);
    User user = (User) userMapper.selectById(1);
    Assertions.assertEquals(user.getId().longValue(), 1L);
}
Also used : User(com.baomidou.mybatisplus.samples.reduce.springmvc.entity.User) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) City(com.baomidou.mybatisplus.samples.reduce.springmvc.entity.City) Test(org.junit.Test)

Example 8 with BaseMapper

use of com.baomidou.mybatisplus.core.mapper.BaseMapper 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);
    }
}
Also used : BindingException(org.apache.ibatis.binding.BindingException) CollectionUtil(cn.hutool.core.collection.CollectionUtil) SpringUtils(com.github.yiuman.citrus.support.utils.SpringUtils) MapperRegistry(org.apache.ibatis.binding.MapperRegistry) CrudUtils(com.github.yiuman.citrus.support.utils.CrudUtils) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SqlSessionTemplate(org.mybatis.spring.SqlSessionTemplate) Serializable(java.io.Serializable) TableInfoHelper(com.baomidou.mybatisplus.core.metadata.TableInfoHelper) Objects(java.util.Objects) CrudMapper(com.github.yiuman.citrus.support.crud.mapper.CrudMapper) Slf4j(lombok.extern.slf4j.Slf4j) TypeUtil(cn.hutool.core.util.TypeUtil) TableInfo(com.baomidou.mybatisplus.core.metadata.TableInfo) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) Map(java.util.Map) ArrayUtil(cn.hutool.core.util.ArrayUtil) Tree(com.github.yiuman.citrus.support.model.Tree) CrudService(com.github.yiuman.citrus.support.crud.service.CrudService) BaseService(com.github.yiuman.citrus.support.crud.service.BaseService) TreeMapper(com.github.yiuman.citrus.support.crud.mapper.TreeMapper) SqlSessionTemplate(org.mybatis.spring.SqlSessionTemplate) MapperRegistry(org.apache.ibatis.binding.MapperRegistry) BaseMapper(com.baomidou.mybatisplus.core.mapper.BaseMapper) BindingException(org.apache.ibatis.binding.BindingException)

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