开发者

hibernate and selective lazy loading

开发者 https://www.devze.com 2023-01-26 08:15 出处:网络
i have the following class structure mapped to my database, note in my diagram b is a one to many child of A, etc.

i have the following class structure mapped to my database, note in my diagram b is a one to many child of A, etc.

a
-b
--c
-d
--e
---f
---g

now, when i get my result set back from hibern开发者_Go百科ate, i plug it into jibx to be marshalled and sent to the client. my problem is when jibx tries to access the lazy load records, i get an exception because by that point its disconnected from the hibernate session.

now to make it even worse, there are transactions where i want to have all records of class a, b, c, d, but none of e, f, g. but the next query may want all of a, d, e, f, g and none of b, or c and the next query all of a, d, g and none of the rest.

so, my DAO class looks like this

public class SurveyNameDAO extends HibernateDaoSupport
{
public List<SurveyName> getPermittedSurveys(String userName)
    {
        StringBuffer sql = new StringBuffer();
        sql.append("select distinct sn ");
        sql.append("from SurveyName as sn, SurveyNameStore name_store ");
        sql.append("where name_store.showStoreLocation.storeName in (select ng.pnName ");
        sql.append("from NukeGroups as ng, NukeUsers as nu ");
        sql.append("where nu.pnName = '" + userName + "')");

        SurveyName loc = null;
        List l = getHibernateTemplate().find(sql.toString());

        return l;

    }
}

basic question is how can i modify this method (and many like it) where i can add some kind of indicators saying to load the return class in the manner i spoke above and then completely disconnect from hibernate and forget about lazy loading for when i send it to jibx.


By default hibernate loads the child objects Lazily. That means, Only the object queried will be loaded, i.e. in your example, the SurveyName object will be loaded.

Assuming SurveyName corresponds to entity A in the tree you've shown above, only the id's of B and D which are the directly referenced objects in A will be loaded.

You can read more about this What is lazy loading in Hibernate? and Explanations of lazy loading.

As for your question, you need to fetch the referenced objects inside the session. So in your example you need to iterate over the list l and fetch the SurveyNameStore objects on each item in the list so that they are loaded.

After this, you can pass the SurveyName object and the SurveyNameStore reference will be available to send to the client.

Similarly you load all the objects you need in each method separately.

I don't have your class structure, so i can't give you the exact solution, but working on these lines should solve your problem, if you've not solved it already.

0

精彩评论

暂无评论...
验证码 换一张
取 消