gpt4 book ai didi

java - Hibernate OneToMany 列表为空

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:49 26 4
gpt4 key购买 nike

我的实体:

客户.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;
}

发票.类

@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;
}

收据类

@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()));

将 Criteria 与 ResultTransformer 一起使用也可以给我正确的收据大小

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(),但收据集仍然是空的。

那么..我的映射或者我的想法哪里错了?

谢谢

最佳答案

查看 hibernate sql 日志,我发现收据实体中的附加 @ManyToOne 映射出现了错误。

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

尽管我认为没有它它应该也能工作,因为 Java 文档说可选默认为 true。

关于java - Hibernate OneToMany 列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com