休眠:@ManyToOne(fetch = FetchType.LAZY)不适用于非主键引用列 [英] Hibernate: @ManyToOne(fetch = FetchType.LAZY) does not work on non-primary key referenced column
问题描述
我有两个表格: Order [OrderId(PK),OrderShipmentCode,...]
和 Shipment [ShipmentId(PK),ShipmentCode, ...
。
在 Order
类中,声明了
$ b
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name =OrderShipmentCode,referencedColumnName =ShipmentCode,insertable = false,updatable = false,nullable = false)
private装运货物;
当我得到 Order
的列表时, Shipment
也被加载(我看到很多单独的SELECT查询)。但是我希望 Shipment
被延迟加载,而不是与 Order一起被提取。
对于其他表,如果被引用的列是主键,那么结果如预期(使用延迟加载)。在我的情况下, ShipmentCode
不是 Shipment
表的主键,Hibernate不使用延迟加载。 / p>
你能告诉我如何实现这个目标吗?
编辑:
查询代码如下:
Criteria criteria = HibernateUtil.getSessionFactory()。getCurrentSession()。createCriteria(Order。类);
列表结果= criteria.list();
SQL查询有:1个用于 Order
table和一堆SELECT语句用于 Shipment
试试这个:
Criteria criteria = HibernateUtil.getSessionFactory()
.getCurrentSession()
.createCriteria(Order。 class)
.setFetchMode(shipment,FetchMode.LAZY);
I have 2 tables: Order [OrderId(PK), OrderShipmentCode, ...]
and Shipment[ShipmentId(PK), ShipmentCode, ...]
.
In Order
class, I declared shipment
field as follows:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OrderShipmentCode", referencedColumnName = "ShipmentCode", insertable = false, updatable = false, nullable = false)
private Shipment shipment;
When I get the list of Order
, the Shipment
is also loaded (I saw many separate SELECT queries). But I want the Shipment
to be lazy loaded, not to be fetched together with Order
.
For other tables, if the referenced column is primary key then the results are as expected (Lazy-loading is used). In my case, ShipmentCode
is not Primary Key of Shipment
table, and lazy-loading is not used by Hibernate.
Could you show me how to accomplish that goal?
EDIT: The Query code is as bellow:
Criteria criteria = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Order.class);
List result = criteria.list();
SQL queries are: 1 SELECT statement for Order
table and a bunch of SELECT statement for Shipment
Try this:
Criteria criteria = HibernateUtil.getSessionFactory()
.getCurrentSession()
.createCriteria(Order.class)
.setFetchMode("shipment", FetchMode.LAZY);
这篇关于休眠:@ManyToOne(fetch = FetchType.LAZY)不适用于非主键引用列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!