Browse Source

【新增】增加一个table唯一值校验的自定义注解

fengshuonan 4 years ago
parent
commit
6005c1766c

+ 11 - 0
guns-base-support/guns-core/src/main/java/cn/stylefeng/guns/core/context/system/SystemContext.java

@ -114,4 +114,15 @@ public interface SystemContext {
     * @date 2020/8/9 14:18
     * @date 2020/8/9 14:18
     */
     */
    List<String> getDictCodesByDictTypeCode(String... dictTypeCodes);
    List<String> getDictCodesByDictTypeCode(String... dictTypeCodes);
    /**
     * 校验某个表中,某一列是否存在重复的值
     * <p>
     * 一般用于唯一code校验
     *
     * @return true-是唯一的值,false-不是唯一的
     * @author fengshuonan
     * @date 2020/8/9 21:41
     */
    boolean tableUniValueFlag(String tableName, String columnName, String value);
}
}

+ 67 - 0
guns-base-support/guns-core/src/main/java/cn/stylefeng/guns/core/validation/unique/TableUniqueValue.java

@ -0,0 +1,67 @@
/*
Copyright [2020] [https://www.stylefeng.cn]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处,作者声明等。
4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点,可申请商业授权,获取Guns商业授权许可,请在官网购买授权,地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.core.validation.unique;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
 * 验证表的的某个字段值是否在是唯一值
 *
 * @author stylefeng
 * @date 2020/4/14 23:49
 */
@Documented
@Constraint(validatedBy = TableUniqueValueValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableUniqueValue {
    String message() default "库中存在重复编码,请更换该编码值";
    Class[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    /**
     * 表名称,例如 sys_user
     */
    String tableName();
    /**
     * 列名称,例如 user_code
     */
    String columnName();
    @Target({ElementType.FIELD, ElementType.PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        TableUniqueValue[] value();
    }
}

+ 54 - 0
guns-base-support/guns-core/src/main/java/cn/stylefeng/guns/core/validation/unique/TableUniqueValueValidator.java

@ -0,0 +1,54 @@
/*
Copyright [2020] [https://www.stylefeng.cn]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处,作者声明等。
4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点,可申请商业授权,获取Guns商业授权许可,请在官网购买授权,地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.core.validation.unique;
import cn.stylefeng.guns.core.context.system.SystemContextHolder;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
 * 验证表的的某个字段值是否在是唯一值
 *
 * @author stylefeng
 * @date 2020/4/14 23:49
 */
public class TableUniqueValueValidator implements ConstraintValidator<TableUniqueValue, String> {
    private String tableName;
    private String columnName;
    @Override
    public void initialize(TableUniqueValue constraintAnnotation) {
        this.tableName = constraintAnnotation.tableName();
        this.columnName = constraintAnnotation.columnName();
    }
    @Override
    public boolean isValid(String fieldValue, ConstraintValidatorContext context) {
        return SystemContextHolder.me().tableUniValueFlag(tableName, columnName, fieldValue);
    }
}

+ 36 - 0
guns-base-support/guns-system/src/main/java/cn/stylefeng/guns/sys/core/context/SystemContextImpl.java

@ -26,6 +26,7 @@ package cn.stylefeng.guns.sys.core.context;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import cn.stylefeng.guns.core.context.system.SystemContext;
import cn.stylefeng.guns.core.context.system.SystemContext;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.sys.modular.auth.service.AuthService;
import cn.stylefeng.guns.sys.modular.auth.service.AuthService;
@ -36,9 +37,14 @@ import cn.stylefeng.guns.sys.modular.role.service.SysRoleService;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.param.SysUserParam;
import cn.stylefeng.guns.sys.modular.user.param.SysUserParam;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.List;
/**
/**
@ -50,6 +56,8 @@ import java.util.List;
@Component
@Component
public class SystemContextImpl implements SystemContext {
public class SystemContextImpl implements SystemContext {
    Log log = Log.get();
    @Resource
    @Resource
    private AuthService authService;
    private AuthService authService;
@ -62,6 +70,9 @@ public class SystemContextImpl implements SystemContext {
    @Resource
    @Resource
    private SysDictDataService sysDictDataService;
    private SysDictDataService sysDictDataService;
    @Resource
    private DruidDataSource druidDataSource;
    @Override
    @Override
    public String getNameByUserId(Long userId) {
    public String getNameByUserId(Long userId) {
        return sysUserService.getNameByUserId(userId);
        return sysUserService.getNameByUserId(userId);
@ -112,4 +123,29 @@ public class SystemContextImpl implements SystemContext {
        return sysDictDataService.getDictCodesByDictTypeCode(dictTypeCodes);
        return sysDictDataService.getDictCodesByDictTypeCode(dictTypeCodes);
    }
    }
    @Override
    public boolean tableUniValueFlag(String tableName, String columnName, String value) {
        try {
            DruidPooledConnection connection = druidDataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select count(*) from " + tableName + " where " + columnName + " = ?");
            preparedStatement.setString(1, value);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                long sumValue = resultSet.getLong(1);
                if (sumValue == 0L) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } catch (SQLException throwables) {
            log.error("执行sql错误!", throwables);
        }
        return false;
    }
}
}