Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 614
Nghia Le Avatar asked Jan 09 '15 06:01

Nghia Le


2 Answers

Thd problem is caused by the HHH-13024 issue.

In the true spirit of OSS, you might want to investigate the problem and send a Pull Request with a fix proposal. That's the fastest way of getting an issue fixed.

like image 104
Vlad Mihalcea Avatar answered Nov 08 '22 11:11

Vlad Mihalcea


If you worry about multiple select queries while loading, you can overcome this by using Entity Graphs. please refer to below link for more details https://www.baeldung.com/spring-data-jpa-named-entity-graphs

like image 1
WGSSAMINTHA Avatar answered Nov 08 '22 12:11

WGSSAMINTHA