java - 使用左连接的 Hibernate 标准来过滤结果

标签 java hibernate

使用 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 = 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)

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/

相关文章:

java - hql - 按列表的第一项排序

java - 如何强制 Gradle 使用特定的 jar?

java - 如何在 JSP 中加载主体内的 CSS?

java - 在Eclipse中快速定位产品配置

java - 配置 tomcat/hibernate 以拥有支持 1.2.840.113549.1.5.13 的加密提供程序

java - 为什么在 Controller 或服务中,我们可以访问延迟加载的代理对象,但不能在 AbstractUserDetailsAuthenticationProvider 的子类中访问?

java - 如何获取 Jersey JaxRS 中的所有查询参数?

java - SpringData 和 mongoDb 超时

hibernate - 使用 JPA 和 PostgreSQL 9.0 分组

java - hibernate:如何将变量映射为外键