Hibernate: @ManyToOne(fetch = FetchType.LAZY) does not work on non-primary key referenced column

江枫思渺然 提交于 2019-12-10 01:15:50

问题


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


回答1:


You need to specify optional = false:

@OneToOne(optional = false, fetch = FetchType.LAZY)

or simply turn it into a @ManyToOne:

@ManyToOne(fetch = FetchType.LAZY)



回答2:


Try this:

Criteria criteria = HibernateUtil.getSessionFactory()
                                 .getCurrentSession()
                                 .createCriteria(Order.class)
                                 .setFetchMode("shipment", FetchMode.LAZY);



回答3:


You can use @JsonIgnore over the shipment field of order. If you are giving using MappedBy over shipment field then removing it might solve your issue.



来源:https://stackoverflow.com/questions/27854768/hibernate-manytoonefetch-fetchtype-lazy-does-not-work-on-non-primary-key-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!