java积累

36 阅读1分钟
//防御性编程防止,因自定义异常或AOP特殊处理导致识别不到异常(默认识别RuntimeException和Error)
@Transactional(
        rollbackFor = {Exception.class}
    )
    public boolean saveOrUpdate(T entity) {
        if (null == entity) {
            return false;
        } else {
            //使用反射获取类的信息
            Class<?> cls = entity.getClass();
            //使用TableInfoHelper获取对应映射关系的字段名
            TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
            //如果获取不到直接抛出异常,加newObject[0]是断言要求
            Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
            //获取到主键的字段名如:id
            String keyProperty = tableInfo.getKeyProperty();
            //判空判断
            Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
            //获取到entity实例中主键id这个属性的值
            Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty());
            //判断主键和对应的数据库数据是否为,空就新增,否则更新,因为getById要求Serializable类型的值也因此需要强制类型转换
            return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable)idVal)) ? this.updateById(entity) : this.save(entity);
        }
    }