为我的dto构建复合唯一约束

2vuwiymt  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(134)

我正在尝试为我的java/spring引导rest api构建一个constraintvalidator。
问题是:我必须将一个国家和一个州/省保存到数据库中,但一个国家不能有两个同名的州/省。
因此,我用javax.persistence中的@uniqueconstraint设置了我的域类:state.class,当对象到达我的db时,它工作得很好,但是,我想让它更安全,并构建这个constraintvalidator来对我的请求dto执行同样的操作,我称之为staterequestdto.class。
因为我喜欢尝试使东西泛化,所以我尝试构建一个通用的多约束验证器,就像在dto类上使用一样,传递希望唯一的参数组合,并使用实现constraintvalidator的类,构建一个jpql查询,以查看注解上的参数组合是否已经存在。
这是我的staterequestdto类

@UniqueCombo(combo = {"idCountry", "name"})
public class StateRequestDto {

    @Unique(fieldName = "name", clazz = "State")
    private String name;
    @ExistsId(entityName = "Country")
    private Integer idCountry;

    public StateRequestDto (String name, Integer idCountry) {
        this.name = name;
        this.idCountry = idCountry;
    }

    public State convert(Country country) {
        return new State(name, country);
    }

    public Object getIdCountry() {
        return this.idCountry;
    }

    public String getName() {
        return this.name;
    }
}

以及我的uniquecombo注解:

@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = UniqueComboValidator.class)
public @interface UniqueCombo {
    String message() default "Testing...";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    String[] combo();
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题