java 休眠:@ManyToOne(fetch = FetchType.LAZY) 对非主键引用列不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27854768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate: @ManyToOne(fetch = FetchType.LAZY) does not work on non-primary key referenced column
提问by Nghia Le
I have 2 tables: Order [OrderId(PK), OrderShipmentCode, ...]and Shipment[ShipmentId(PK), ShipmentCode, ...].
我有 2 张桌子:Order [OrderId(PK), OrderShipmentCode, ...]和Shipment[ShipmentId(PK), ShipmentCode, ...].
In Orderclass, I declared shipmentfield as follows:
在Order课堂上,我声明shipment了如下字段:
@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 Shipmentis also loaded (I saw many separate SELECT queries). But I want the Shipmentto be lazy loaded, not to be fetched together with Order.
当我得到 的列表时Order,Shipment也加载了(我看到了许多单独的 SELECT 查询)。但我希望Shipment延迟加载,而不是与Order.
For other tables, if the referenced column is primary key then the results are as expected (Lazy-loading is used). In my case, ShipmentCodeis not Primary Key of Shipmenttable, and lazy-loading is not used by Hibernate.
对于其他表,如果引用的列是主键,则结果如预期(使用延迟加载)。在我的情况下,ShipmentCode不是Shipment表的主键,并且 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 Ordertable and a bunch of SELECT statement for Shipment
SQL 查询是:1 条用于Order表的 SELECT 语句和一组用于表的 SELECT 语句Shipment
回答by Vlad Mihalcea
You need to specify optional = false:
您需要指定optional = false:
@OneToOne(optional = false, fetch = FetchType.LAZY)
or simply turn it into a @ManyToOne:
或者干脆把它变成一个@ManyToOne:
@ManyToOne(fetch = FetchType.LAZY)
回答by shady
Try this:
试试这个:
Criteria criteria = HibernateUtil.getSessionFactory()
.getCurrentSession()
.createCriteria(Order.class)
.setFetchMode("shipment", FetchMode.LAZY);
回答by Syam Dorjee
You can use @JsonIgnoreover the shipment field of order. If you are giving using MappedByover shipment field then removing it might solve your issue.
您可以@JsonIgnore在订单的发货字段上使用。如果您提供使用MappedBy过装运字段,则删除它可能会解决您的问题。

