java - JPA实体:如何检查递归父母
问题描述
我有一个代表一个组的简单实体。
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(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);
推荐阅读
- javascript - 按滚动百分比从上到下垂直移动图像
- sharepoint - Sharepoint 警报不适用于一个站点上的一个用户
- function - 我应该如何解开这组 lapply/sapply/mapply
- c# - Client stops working after sending message and server doesn't wait for mutliple data to come
- asp.net-core - InvalidOperationException: No service for type Microsoft.AspNetCore.Identity.UserManager has been registered error using ASP.NET Identity Server
- python - 将 FPDF 整合到适用于 Android 平板电脑的 Kivy 应用程序中
- swift - 用 SciFormatter 划分两个文本字段
- vb.net - 输入数字的总和与 do 循环直到
- r - 按天分组时间序列/时间戳
- javascript - 如何使用 node.js 替换 json 文件的特定部分