【问题标题】:JPA Entities: how to check recursive parentsJPA实体:如何检查递归父母
【发布时间】:2020-09-17 16:50:45
【问题描述】:

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

 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;
 }

一个组可以是某些组的父组。

在测试期间,我设置了A.parent = A,因此 A 对象处于递归状态。

是否有注解或其他东西可以检查以下约束?

a.id != a.parent.id

【问题讨论】:

标签: java jpa-2.1


【解决方案1】:

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

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

使用验证逻辑创建验证器类以检查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;
    }
}

将此约束应用于实体类 Group。

@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);

【讨论】:

  • 它解决了我的问题。我使用了一些反射和接口来创建一个通用的“checkparentvalidator”
猜你喜欢
  • 1970-01-01
  • 2018-12-08
  • 2020-10-05
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
相关资源
最近更新 更多