9

左外连接应该是从左表中获取所有数据,无论B表是否有匹配的记录,但是如果左表的right_id列为空,则无法获取记录。

我在解释更多

在数据模型中:Order.java,它是我的 LEFT 表,有一对一的关系

@OneToOne(targetEntity = OrderShippingDetail.class, optional=true, cascade = {CascadeType.ALL})
@JoinColumn(name = "SHIPPING_DETAIL_ID", referencedColumnName = "ID")
private OrderShippingDetail shippingDetail;

和 HQL 是:

    hql = "SELECT " +
            "o.id as id, " +
            "o.createTime as createTime, " +
            "o.customerEmailAddress as customerEmailAddress, " +
            "o.customerPhoneNumber as customerPhoneNumber, " +
            "o.customerNote as customerNote, " +
            "o.invoicePrintedFlag as invoicePrintedFlag, " +
            "shippingAddress.address.personName as shippingPersonName, " +
            "shippingDetail.shippingCompany.id as shippingCompanyId, "+
            "shippingDetail.shippingCompany.name as shippingCompanyName, "+
            "shippingDetail.receiptNumber as shippingReceiptNumber, "+
            "shippingDetail.trackingNumber as shippingTrackingNumber, "+
            "shippingDetail.price as shippingPrice, "+
            "o.invoiceNumber as invoiceNumber " + 
        "FROM Order AS o " +
        "LEFT OUTER JOIN o.shippingAddress AS shippingAddress " +
        "LEFT OUTER JOIN o.shippingDetail AS shippingDetail ";

但是只有“SHIPPING_DETAIL_ID”不为空的记录。HQL 有错误吗?它是通过建模 SQL 命令创建的,该命令是在 hibernate 运行时自动创建的。

我找到了这个,

HQL 支持两种形式的关联连接:隐式和显式。

上一节中显示的查询都使用显式形式,即在 from 子句中显式使用 join 关键字。这是推荐的形式。

隐式形式不使用 join 关键字。相反,使用点符号“取消引用”关联。隐式连接可以出现在任何 HQL 子句中。隐式连接导致生成的 SQL 语句中的内部连接。

我删除了 SELECT 部分中的点符号,所以我的新 HQL:

hql = "SELECT " +
                "o.id as id, " +
                "o.createTime as createTime, " +
                "o.customerEmailAddress as customerEmailAddress, " +
                "o.customerPhoneNumber as customerPhoneNumber, " +
                "o.customerNote as customerNote, " +
                "o.invoicePrintedFlag as invoicePrintedFlag, " +
                "shippingDetail, " +
                "o.invoiceNumber as invoiceNumber " + 
            "FROM Order AS o " +
            "LEFT OUTER JOIN o.shippingAddress AS shippingAddress " +
            "LEFT OUTER JOIN o.shippingDetail AS shippingDetail ";

所以,它有效,它返回 Order 表中的所有记录,但是,我不想选择 ShippingDetail 对象中的所有列和关系。我能做些什么来解决这个问题?

4

1 回答 1

8

向查询中添加另一个显式左连接:

SELECT o.id as id, 
...,
shippingCompany.id as shippingCompanyId, 
shippingCompany.name as shippingCompanyName, 
...
FROM Order AS o
LEFT OUTER JOIN o.shippingAddress AS shippingAddress 
LEFT OUTER JOIN o.shippingDetail AS shippingDetail
LEFT OUTER JOIN shippingDetail.shippingCompany AS shippingCompany
于 2013-02-07T23:15:12.057 回答