使用JoinTable和OneToMany的MultipleBagFetchException?

时间:2014-04-15 18:05:25

标签: java hibernate jpa

我有一对一的单向关系,但两个表之间有一个连接表。例如:

父表(CUSTOMER):

+----+------+-----+
| ID | NAME | ... |
+----+------+-----+

加入表(CUSTOMER_TO_PHONE):

+---------+----------+
| CUST_ID | PHONE_ID |
+---------+----------+

儿童表(电话):

+----+-----------+--------+
| ID | AREA_CODE | NUMBER |
+----+-----------+--------+

显然,从SQL的角度来看,您可以执行以下操作:

select C.NAME, P.AREA_CODE, P.NUMBER
from CUSTOMER C, CUSTOMER_TO_PHONE CTP, PHONE P
where C.ID = CTP.CUST_ID and CTP.PHONE_ID = P.ID;

从JPA的角度来看,我试图做到这一点,所以我不必为连接表创建实体类,因此我尝试使用@JoinTable。这是我的尝试:

@Entity @Table(name = "CUSTOMER")
public class Customer {

    @Id
    private long id;

    private String name;

    @JoinTable(
        name = "CUSTOMER_TO_PHONE",
        joinColumns = @JoinColumn(name = "CUST_ID", referencedColumnName = "ID"),
        inverseJoinColumns = @JoinColumn(name = "PHONE_ID", referencedColumnName = "ID"))
    @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true)
    private List<Phone> phoneNumbers;
}

@Entity @Table(name = "PHONE")
public class Phone {

    @Id
    private long id;

    @Column(name = "AREA_CODE")
    private int areaCode;

    private int number;
}

然而,当我尝试加载EntityManager时,这给了我一个可爱的例外: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

我在这里做错了什么?我没有看到它。由于它是单向的,我不认为电话需要某种回馈给客户。

0 个答案:

没有答案