Hibernate mapping setting lazy = 'false'

2019-02-23 18:14发布

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.

2条回答
该账号已被封号
2楼-- · 2019-02-23 19:15

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!

查看更多
Root(大扎)
3楼-- · 2019-02-23 19:21

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
查看更多
登录 后发表回答