我有一个 OneToMany
关系定义如下
class ActionSet {
@OneToMany
List<Action> action;
}
class Action {
ActionSet actionSet;
Boolean isShared;
}
Action 可以在多个 Action 集之间共享,也可以与单个 Action 集相关联。
共享 Action 时,它可能对某些 Action 集很重要,但对其他 Action 集不重要。这里 isImportant
是一个关系属性。我如何在 JPA 中定义这种关系?
最佳答案
基本上您将需要三个实体类,如下所示:
Action 集:
@Entity
public class ActionSet {
@OneToMany(mappedBy = "actionSet")
List<ActionSetAction> action;
}
行动:
@Entity
public class Action {
@OneToMany(mappedBy = "action")
List<ActionSetAction> action;
}
ActionSetAction(代表Join表):
@Entity
public class ActionSetAction {
@ManyToOne
@JoinColumn(name = "action_set_id")
private ActionSet actionSet;
@ManyToOne
@JoinColumn(name = "action_id"
private Action action;
@Column(name ="is_important"
private boolean important;
}
如果您想在数据库级别而不是在内存级别区分重要和不重要的操作集操作,那么您可以考虑使用非 JPA Hibernate 特定的 @Where 注释。
@Entity
public class ActionSet {
@OneToMany(mappedBy = "action")
@Where(clause="is_important = true")
List<ActionSetAction> importantActions;
@OneToMany(mappedBy = "action")
@Where("is_important = false")
List<ActionSetAction> unimportantActions;
}
请注意,我最近回答了一个问题,在该问题中我建议对一个非常相似的问题使用纯 JPA 解决方案。然而,虽然这在 EclipseLink 中有效,但在 Hibernate 中存在问题。
关于java - 在 JPA 中定义关系属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27560469/