问题描述
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
解决方法
您可以创建自定义验证器和类级别注释约束,使用验证api的Constraint注释绑定验证器类。
@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);