应用场景:
我有一张订单表,一张代理商表,我订单表和代理商设置为many-to-one。
public class ProxyCustomer {
private int id;
}
public class Order {
private int id;
private ProxyCustomer proxyCustomer;
}
many-to-one 配置如下:
<many-to-one name="proxyCustomer" column="proxy_customer_id" class="com.pro.entity.ProxyCustomer" not-null="false" fetch="join" lazy="false"/>
执行查询后,为什么list中会返回两个对象,一个是Order对象,一个是ProxyCustomer对象
而我期望只要一个Order对象,因为Order对象里包含了ProxyCustomer对象。
debug 看到的现象如下截图:
我的写法打印出来的sql已经是left join了:
SELECT this_.id AS id21_1_,
this_.order_id AS order2_21_1_,
this_.pipeline_order_id AS pipeline3_21_1_,
this_.reference_id AS reference4_21_1_,
this_.username AS username21_1_,
this_.phone AS phone21_1_,
this_.status AS status21_1_,
this_.type AS type21_1_,
this_.return_code AS return9_21_1_,
this_.return_message AS return10_21_1_,
this_.return_date AS return11_21_1_,
this_.final_price AS final12_21_1_,
this_.creation_date AS creation13_21_1_,
this_.created_by AS created14_21_1_,
this_.updated_date AS updated15_21_1_,
this_.updated_by AS updated16_21_1_,
this_.box_id AS box17_21_1_,
this_.proxy_customer_id AS proxy18_21_1_,
proxycusto2_.id AS id28_0_,
proxycusto2_.updated_date AS updated2_28_0_,
proxycusto2_.username AS username28_0_,
proxycusto2_.password AS password28_0_,
proxycusto2_.name AS name28_0_,
proxycusto2_.company AS company28_0_,
proxycusto2_.contact_person AS contact7_28_0_,
proxycusto2_.contact_phone AS contact8_28_0_,
proxycusto2_.address AS address28_0_,
proxycusto2_.balance AS balance28_0_,
proxycusto2_.security_deposit AS security11_28_0_,
proxycusto2_.warn_balance AS warn12_28_0_,
proxycusto2_.parent_proxy_customer AS parent13_28_0_,
proxycusto2_.api_status AS api14_28_0_,
proxycusto2_.status AS status28_0_,
proxycusto2_.sms_notify AS sms16_28_0_,
proxycusto2_.email_notify AS email17_28_0_,
proxycusto2_.email_notify_list AS email18_28_0_,
proxycusto2_.phone_notify_list AS phone19_28_0_,
proxycusto2_.creation_date AS creation20_28_0_,
proxycusto2_.created_by AS created21_28_0_,
proxycusto2_.updated_by AS updated22_28_0_
FROM pro_order this_
LEFT OUTER JOIN pro_proxy_customer proxycusto2_
ON this_.proxy_customer_id=proxycusto2_.id;
看你的sql就很明白啊,因为你的代理商表有2条满足这个订单,sql肯定返回2条查询结果,这很正常。
正常的hibernate得关联查询应该是有2个sql而不是合并成一个sql查询。
LEFT OUTER JOIN 一个表满足条件的行,和另一个表的所有行
左外连接 包含左边表的全部行(不管右边的表中是否存在与它们匹配的行),以及右边表中全部匹配的行