one to one mapping using primary key join column

牧云@^-^@ 提交于 2019-12-02 08:02:34
Dragan Bozanovic

A) It is a little bit weird, and Hibernate could do it better. However, this is due to the fact that Employee is loaded eagerly in EmployeeDetail, and Hibernate wants to avoid additional queries to load the corresponding employee for each EmployeeDetail. It could do it better because the corresponding employees are already loaded with the first query.

This should disappear if you apply my advice in B).

B) By default, one-to-one associations are eager in JPA. To make it lazy:

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Employee empl;

However, keep in mind the behavior of one-to-one associations described here. If Hibernate cannot determine whether the proxied object in one-to-one relation exists or is null, then additional query will be executed anyway to check this.

To overcome this, if empl is mandatory for each EmployeeDetail (and it is in your use case, an employee detail cannot exist without the employee), then indicate it in the association mapping:

@OneToOne(fetch = FetchType.LAZY, optional = false)
@PrimaryKeyJoinColumn
private Employee empl;

This way Hibernate will make a proxy containing only Employee id when loading EmployeeDetail entity instances without querying employee table at all.

Can someone please clarify why when executing the following query session.createQuery("from Employee").list();

This should be happening because your employee table must have 3 entries. Since it is a one-to-one mapping, for each row returned from employee it will fire a query to fetch its employeedetail. So the three queries.

B) also, for the query session.createQuery("from EmployeeDetail").list();

Proxies are only created for lazily loaded entities.

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