簡體   English   中英

使用左聯接休眠條件以過濾結果

[英]Hibernate criteria using left join to filter results

帶有Hibernate的JSF應用程序

有沒有一種方法可以使用聯接來過濾條件列表返回的結果?
示例:我有2張桌子。 訂單和客戶。

@Entity(name = "order")
public class Order
{
    @Id
    private int id;
    private String billingCustomerId;
    private String shippingCustomerId;
    private Date orderDate;
    ....
}

@Entity(name = "customer")
public class Customer
{
    @Id
    private String id;
    private String name;
    private String emailAddress

    ....
}

我需要為缺少電子郵件地址的客戶返回所有訂單,以及order.billingCustomerId = nullorder.shippingCustomerId = null所有訂單。

客戶可以在billingCustomerIdshippingCustomerId上進行匹配。

我將使用的SQL

select o.* from order as o
LEFT  join customer as c1 on o.billingCustomerId = c1.id
LEFT  join customer as c2 on o.shippingCustomerId= c2.id
where (o.billingCustomerId is null and o.shippingCustomerId is null) or 
(o.billingCustomerId is not null and c1.emailAddress is null) or
(o.shippingCustomerIdis not null and c2.emailAddress is null)

休眠標准

Criteria criteria1 = session.createCriteria(Order.class);
criteria.add(Restrictions.and(Restrictions.isNull("billingCustomerId"),
Restrictions.isNull("shippingCustomerId"));
List<Order> = criteria.list();

這將返回開單/裝運客戶= null的訂單列表。

我如何更改標准以包括缺少電子郵件地址的客戶的訂單?

Disjunction disjunciton = Restrictions.disjunction();
Criteria criteria = session.createCriteria(Order.class);
disjunciton.add(Restrictions.and(Restrictions.isNull("billingCustomerId"),
        Restrictions.isNull("shippingCustomerId")));
disjunciton.add(...


                ...)
criteria.add(disjunciton);
List<Order> = criteria.list();

我無法找到在列上進行聯接的示例,而只能在表具有公共鍵的地方找到。

我問了一個問題: Hibernate無法使復合鍵起作用,並發現Hibernate只能在通過關聯2個對象創建的列上創建聯接。 我將在答案中添加更多內容,以提供更多有用的信息,但是您遇到的最佳選擇是使用上面顯示的查詢來執行Session.createSQLQuery()。 然后,在運行查詢之前,先放置Query.addEntity(Order.class).addEntity(Customer.class)。 只要查詢返回正確的行以正確填寫Java對象,Hibernate就會自動填充它們。 如果這樣不起作用,您仍然可以自己檢索數據並手動進行填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM