JPA 实体:如何检查递归 parents

JPA Entities: how to check recursive parents

我有一个代表组的简单实体。

 public class Group {
 Long id;
 String name;

 @JoinColumn(name = "idparent", nullable = true, referencedColumnName = "ID")
 @ManyToOne(targetEntity = Group.class, fetch = FetchType.EAGER, cascade = {}, optional = true)
 private Group parent;
 }

一个组可以是一些组的parent。

在测试期间我设置了 A.parent = A,所以 A object 属于递归。

是否有注释或其他内容来检查以下约束?

a.id != a.parent.id

您可以创建自定义验证器和class级别注释约束,使用验证api的约束注释绑定验证器class。

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

使用验证逻辑创建验证器 class 以检查 a.id != a.parent.id

public class GroupConstraintValidator implements ConstraintValidator<GroupConstraint, Group>{

    @Override
    public boolean isValid(Group object, ConstraintValidatorContext context) {
         if (!(object instanceof Group)) {
                throw new IllegalArgumentException("@CustomConstraint only applies to TestA");
            }
         Group group = (Group) object;
         if (group.getParent() != null && group.getParent().getId() == group.getId()) {
             return false; 
         }
         return true;
    }
}

将此约束应用于实体 class、组。

@Entity
@GroupConstraint
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name= "ID",unique = true)
    private Long id;

    private String name;

    @JoinColumn(name = "IDPARENT", nullable = true, referencedColumnName = "ID")
    @ManyToOne(targetEntity = Group.class, fetch = FetchType.EAGER, cascade = {}, optional = true)
    private Group parent;

现在,验证提供程序应该在生命周期回调期间通过约束违反,即当子项引用自身时。

Group child = new Group();
//set attributes
child.setParent(child);
em.persist(child);