Jpa OneToMany有条件

时间:2013-05-01 18:30:35

标签: jpa jpa-2.0 spring-data-jpa

我有两张桌子:

第一个是"人物":

  • 为person_id,
  • person_name

第二个是" PersonsGraphs":

  • person_id1,
  • person_id2,
  • relation_type

我正在寻找一种建立家谱的方法"。

我的第一个选项是:将personGraphs加载到HashTable中,然后递归构建树。

我提出的第二个选项:使用@OneToMany jpa-relation。这可以工作,但有时候我想要/不想包含一些relation_types。是否有任何选项可以让我在使用@OneToMany时为@JoinTable关系设置一些条件?

谢谢! 橡木

2 个答案:

答案 0 :(得分:1)

我建议创建一个Relationship类来为连接表建模。

Person - OneToMany - 关系 - 关系 - ManyToOne源 - ManyToOne目标

在EclipseLink中,您可以将表达式条件添加到任何关系映射

http://wiki.eclipse.org/EclipseLink/Examples/JPA/MappingSelectionCriteria

答案 1 :(得分:0)

尝试使用Hibernate @Where annotation,例如:

@Entity
public class Person {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    @ManyToOne
    private Person parent;

    @Where(clause = "gender = 'MALE'")
    @OneToMany(mappedBy = "person")
    private List<Person> sons;

    @Where(clause = "gender = 'FEMALE'")
    @OneToMany(mappedBy = "person")
    private List<Person> daughters;
}

public enum Gender {
   MALE, FEMALE
}