左外连接应该从左表中获取所有数据,无论是否存在来自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对象中的所有列和关系。我该怎么做才能解决这个问题?
答案 0 :(得分:7)
在查询中添加另一个显式左连接:
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