使用 Hibernate 的 JSF 应用程序
有没有办法使用联接来过滤条件列表返回的结果?
示例:我有 2 张 table 。订单和客户。
@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 = null
和 order.shippingCustomerId = null
的所有订单。
客户可以匹配 billingCustomerId
或 shippingCustomerId
。
我会使用的 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)
hibernate 标准
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();
我无法找到连接列的示例,但仅限于表具有公共(public)键的情况。
最佳答案
我问了这个问题:Hibernate trouble getting composite key to work并且发现 Hibernate 只能在通过关联 2 个对象创建的列上创建联接。我将在我的答案中添加更多内容,以提供更多有用的信息,但您的情况的最佳选择是使用上面显示的查询执行 Session.createSQLQuery() 。然后在运行查询之前放置 Query.addEntity(Order.class).addEntity(Customer.class)。只要您的查询返回正确的行以正确填充 Java 对象,Hibernate 就可以自动填充它们。如果这不起作用,您仍然可以检索数据并自行手动填充。
关于java - 使用左连接的 Hibernate 标准来过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797768/