1

我有一个具有以下字段的数据库实体 Person:

  1. ID
  2. 父亲
  3. 母亲

而且我需要创建带有字段子项的 JPA 实体类。像这样的东西:

@Entity
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "father")
    private Integer fatherID;

    @Column(name = "mother")
    private Integer motherID;

    @OneToMany(mappedBy = "fatherId")
    private List<Person> children;
    }

但问题是我还需要在mappedBy属性中确定母亲。结果可能如下所示:

SELECT * FROM person WHERE father = id OR mother = id

有人可以帮我解决这个问题吗?使用 JPA 可以完成这项任务吗?

4

3 回答 3

1

您不能将“mappedBy”设置为非对象类型(因为这不是双向关系)。您必须具有 Person 类型(不是 Integer)的“mother”和“father”字段才能具有双向关系。得到父亲和母亲是微不足道的

于 2012-09-19T15:16:21.700 回答
0

Apart from mapping issues that have been pointed out...

Not a JPA expert but I don't think JPA has this case considered directly. I would solve this using two mappings and an auxiliar fake getter. Sample below:

@OneToMany(mappedBy = "father")
private List<Person> childrenIfFather();

@OneToMany(mappedBy = "mother")
private List<Person> childrenIfMother();

public getChildren() {
    if (childrenIfFather != null) return childrenIfFather();
    else return childrenIfMother();
}
于 2012-09-19T18:11:52.467 回答
0

尝试使用 EJBQL(或者此时是 JPQL?)来解决它:

  SELECT p FROM Person p WHERE p.father = ?1 OR p.mother = ?2

另外,我会考虑使用不是整数的东西作为id。从长远来看,它真的会咬你一口(可能是 long 或 BigInteger)。

于 2012-09-19T15:03:01.933 回答