2012-09-10 49 views
0

我想如下Hibernate註解 - 標準查詢 - 懶加載失敗的屬性

用於描述代碼示例如下 比爾類

public class Bill { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 
    private long billNumber; 
    private BillType billType; 
    @OneToOne 
    private Customer billCustomer; 

//getter and setter omitted 
} 

2類關聯和客戶類的定義是

public class Customer { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 
    private String customerRef; 
    @OneToMany(fetch = FetchType.EAGER) 
    private List<Bill> customerBills;} 

當我嘗試使用標準API檢索對象時,會關聯相關對象。

Bill bill = (Bill) session.createCriteria(Bill.class) 
       .add(Restrictions.eq("billNumber", BILL_NUMBER)).uniqueResult(); 

當我驗證與客戶相關的賬單的大小時,它被視爲空。 (但1張紙幣被關聯到客戶)

Assert.assertEquals(1,bill.getBillCustomer().getCustomerBills().size()); 

(上述條件失敗),但是當我用其他方式證實,它成功

List<Bill> billList = session.createCriteria(Customer.class) 
       .add(Restrictions.eq("customerRef",CUSTOMER_REF)).list(); 
     Assert.assertEquals(1,billList.size()); 

我急切裝載的對象。我無法弄清楚我錯過了什麼?

回答

1

你的映射是錯誤的。如果該關聯是一對多雙向關聯,則一方必須將其定義爲OneToMany,另一方作爲ManyToOne(而不是OneToOne)。

此外,雙向關聯總是擁有所有者方和反方。反面是具有mappedBy屬性的那一面。在OneToMany的情況下,反面必須是一面。所以映射應該是:

@ManyToOne 
private Customer billCustomer; 

... 

@OneToMany(fetch = FetchType.EAGER, mappedBy = "billCustomer") 
private List<Bill> customerBills; 

該映射在hibernate documentation中描述。

+0

該死,遲到2分鐘。 :) –