Hibernate OneToMany列表为空

时间:2016-03-11 08:50:55

标签: java hibernate jpa

我的实体:

Customer.class

@Entity
@Table(name="customer", schema = "pbis", catalog = "feivel")
public class Customer {

    @Id
    @Column(name = "customerid")
    private long id;
    ...
    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
    private Set<Invoice> invoices;

    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<Receipt> receipts;
}

Invoice.class的

@Entity
@Table(name="invoice", schema = "pbis", catalog = "feivel")
public class Invoice {
    @Id
    @Column(name = "invoicenumber")
    private long invoiceNumber;

    @ManyToOne
    @JoinColumn(name = "customerid", insertable = false, updatable = false)
    private Customer customer;
}

Receipt.class

@Entity
@Table(name = "receipts", schema = "pbis", catalog = "feivel")
public class Receipt {
    @EmbeddedId
    private ReceiptId id;

    @ManyToOne
    @JoinColumn(name = "customerid", insertable = false, updatable = false)
    private Customer customer;

一个简单的Hibernate查询

SELECT c FROM Customer WHERE c.id = :id

我得到c.getInvoices().size();的正确大小 但是c.getReceipts().size();返回零

当我使用带有相同查询的eclipselink时,我会得到正确大小的收据和发票。

EntityManagerFactory emf = Persistence.createEntityManagerFactory("eclipselink");
EntityManager em = emf.createEntityManager();

javax.persistence.Query q = em.createQuery("SELECT c FROM Customer c WHERE c.id = :id");
q.setParameter("id", Long.valueOf(event.getText()));

对ResultTransformer使用Criteria也给了我正确的receipts.size

Criteria c = session.createCriteria(Customer.class);
c.add(Restrictions.eq("id", Long.valueOf(event.getText())));
c.setFetchMode("receipts", FetchMode.JOIN);
c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
for (Object o : c.list()) {
    Customer r = (Customer) o;
    System.out.println(r.getReceipts().size());
}

使用SELECT r FROM Receipt WHERE r.customer.id = :id,我得到了正确的r.getCustomer(),但收据集仍为空。

那么..我的映射wron或我的想法在哪里?

谢谢

1 个答案:

答案 0 :(得分:0)

查看hibernate sql日志,我发现Receipt Entity中的其他@ManyToOne映射有问题。

我在映射中添加了optional = true,现在我得到了正确的配方集大小。

虽然我认为它应该没有它,但因为Java文档说可选默认为true。