How to lazy load a one-to-one composition via hql

别来无恙 提交于 2019-12-04 20:28:44

I've fixed this problem.

What I did was to create turn the field EntityA#propertyB into a Set with the name EntityA#propertyBs. But I retained the EntityA#getPropertyB() and EntityA#setPropertyB(EntityB propertyB) accessor methods.

The method bodies of those accessor methods are now something like this:

public EntityB getPropertyB() {
    return CollectionUtils.get(propertyBs, 0);
}

public void setPropertyBs(EntityB propertyB) {
    propertyBs= Collections.singleton(propertyB);
}

Then in my mapping, I mapped the set EntityA#propertyBs and specify the access to 'field'.

<set name="scheduledAdInfos" lazy="true" fetch="subselect" access="field" cascade="none" inverse="true">
    <key column="pk_a"/>
    <one-to-many class="EntityB"/>
</set>

With this setup, you can now create a lazy mapping from the owning POJO (EntityA) to the owned POJO (EntityB) even if TABLE_A is owned by TABLE_B.

Short answer: No you cannot do that, at least not without changing the database and the mapping. You basically have to reverse the one-to-one mapping and the foreign key relation to work in the way you want.


Longer answer: Hibernate can lazy load associations. The way it does this is by injecting a proxy object that holds the ID of the referenced object.

In your case, the mapping is such that the foreign-key column is in TABLE_B, that is, where you use the many-to-one mapping. So if you load a B, hibernate finds the FK reference in the fk_a column and can create a proxy that holds this value. When the proxy is accessed the corresponding entity is loaded.

What if a record from table A is selected? Hibenate will create an A object, but to be able to fill the propertyB, it will have to look into the TABLE_B, to find the corresponding row with fk_a=a.id. There is no other way for Hibernate to find out what record to load at lazy loading time.

Actually, this would be an improvement for Hibernate, since it should also be able to do the loading on other unique keys while lazy loading, but the current implementation does not allow this, maybe you can raise an issue.

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