Hibernate mapping setting lazy = 'false'

老子叫甜甜 提交于 2019-12-01 05:34:18

问题


In hibernate mapping, I have set the property lazy="false", and this fetches all the child records of the parent.

This is being used throughout the application.
This creates a performance issue at a particular module of my application, wherein I would like to fetch only the parent record.

I cant change the lazy property to true since it's being used at many other places. Is there a way to fix this?

Do let me know if any more info is required.


回答1:


These is no such feature in hibernate as it respects your lazy="false". So, what can I suggest to address your requirement is extends your querying class with another dummy concrete class and define mapping for that class without that child association in it.

let say you have class Parent with Child mapping in it

class Parent{

     private List<Child> kids;

}

and mapping for Parent you have is

<class name="Parent" table="PARENT">
// other properties
// child mapping
   <set name="kids" table="KIDS" lazy="false">
       <key column="parent_id"/>
       <one-to-many class="Child"/>
   </set>
</class>

Then you can create another class which extends Parent class

class MinimalParent extends Parent{
   // leave implementation as blank
}

Then map it as bellow

<class name="MinimalParent" table="PARENT">
    // other properties
    // do not map child in this
</class>

And use this MinimalParent class wherever you require just parent object. hope you got it!




回答2:


You should probably set lazy="true" to fetch only parent as a default, and use JPQL queries with "fetch join" to fetch parent together with children wherever it is required, e.g.:

SELECT mag FROM Magazine mag JOIN FETCH mag.articles WHERE mag.id = 1


来源:https://stackoverflow.com/questions/8815209/hibernate-mapping-setting-lazy-false

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