我的OneToMany
关系定义如下
class ActionSet {
@OneToMany
List<Action> action;
}
class Action {
ActionSet actionSet;
Boolean isShared;
}
可以跨多个操作集共享操作,也可以将操作与单个actionSet相关联。
当共享某个操作时,它对某些操作集很重要,但对其他操作集则不重要。这里isImportant
是一个关系属性。如何在JPA中定义这种关系?
答案 0 :(得分:0)
基本上你需要三个实体类,如下所示:
ActionSet:
@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中存在问题。