Prevent Dozer from triggering Hibernate lazy loading
Asked Answered
S

6

18

I am using Spring transactions so the transaction is still active when POJO to DTO conversion occurs.

I would like to prevent Dozer from triggering lazy loading, so that hidden sql queries never occur : all fetching has to be done explicitly via HQL (to get the best control on performances).

  1. Is it a good practice (I can't find it documented anywhere) ?

  2. How to do it safely ?

I tried this before DTO conversion :

PlatformTransactionManager tm = (PlatformTransactionManager) SingletonFactoryProvider.getSingletonFactory().getSingleton("transactionManager");
tm.commit(tm.getTransaction(new DefaultTransactionDefinition()));

I don't know what happens to the transaction, but the Hibernate session doesn't get closed, and the lazy loading still occurs.

I tried this :

SessionFactory sf = (SessionFactory) SingletonFactoryProvider.getSingletonFactory().getSingleton("sessionFactory");
sf.getCurrentSession().clear();
sf.getCurrentSession().close();

And it prevents lazy loading, but is it a good practice to manipulate session directly in the application layer (which is called "facade" in my project) ? Which negative side effects should I fear ? (I've already seen that tests involving POJO -> DTO conversions could no more be launched through AbstractTransactionnalDatasource Spring test classes, because this classes try to trigger a rollback on a transaction which is no more linked to an active session).

I've also tried to set propagation to NOT_SUPPORTED or REQUIRES_NEW, but it reuse the current Hibernate session, and doesn't prevent lazy loading.

Stolen answered 5/4, 2011 at 13:11 Comment(0)
K
26

The only generic solution I have found for managing this (after looking into Custom Converters, Event Listeners & Proxy Resolvers) is by implementing a Custom Field Mapper. I found this functionality tucked away in the Dozer API (I don't believe it is documented in the User Guide).

A simple example is as follows;

public class MyCustomFieldMapper implements CustomFieldMapper 
{
    public boolean mapField(Object source, Object destination, Object sourceFieldValue, ClassMap classMap, FieldMap fieldMapping) 
    {       
        // Check if field is a Hibernate collection proxy
        if (!(sourceFieldValue instanceof AbstractPersistentCollection)) {
            // Allow dozer to map as normal
            return false;
        }

        // Check if field is already initialized
        if (((AbstractPersistentCollection) sourceFieldValue).wasInitialized()) {
            // Allow dozer to map as normal
            return false;
        }

        // Set destination to null, and tell dozer that the field is mapped
        destination = null;
        return true;
    }   
}

This will return any non-initialized PersistentSet objects as null. I do this so that when they are passed to the client I can differentiate between a NULL (non-loaded) collection and an empty collection. This allows me to define generic behaviour in the client to either use the pre-loaded set, or make another service call to retrieve the set (if required). Additionally, if you decide to eagerly load any collections within the service layer then they will be mapped as usual.

I inject the custom field mapper using spring:

<bean id="dozerMapper" class="org.dozer.DozerBeanMapper" lazy-init="false">
    <property name="mappingFiles">
        ...
    </property>
    <property name="customFieldMapper" ref="dozerCustomFieldMapper" />
</bean>
<bean id="dozerCustomFieldMapper" class="my.project.MyCustomFieldMapper" />

I hope this helps anyone searching for a solution for this, as I failed to find any examples when searching the Internet.

Kalahari answered 11/5, 2011 at 11:38 Comment(2)
Thanks, this is great, I can even confirme it is not documented anywhere else than here : google.fr/search?q=CustomFieldMapper+PersistentSetStolen
Also, in a recent version of Dozer (5.3.0), there is an other way to do it (sourceforge.net/tracker/…)Stolen
C
10

A variation on the popular version above, makes sure to catch both PersistentBags, PersistentSets, you name it...

public class LazyLoadSensitiveMapper implements CustomFieldMapper {

public boolean mapField(Object source, Object destination, Object sourceFieldValue, ClassMap classMap, FieldMap fieldMapping) {
    //if field is initialized, Dozer will continue mapping

    // Check if field is derived from Persistent Collection
    if (!(sourceFieldValue instanceof AbstractPersistentCollection)) {
        // Allow dozer to map as normal
        return false;
    }

    // Check if field is already initialized
    if (((AbstractPersistentCollection) sourceFieldValue).wasInitialized()) {
        // Allow dozer to map as normal
        return false;
    }

    return true;
}

}

Cormier answered 11/1, 2013 at 19:36 Comment(0)
E
5

I didn't get the above to work (probably different versions). However this works fine

public class HibernateInitializedFieldMapper implements CustomFieldMapper {
    public boolean mapField(Object source, Object destination, Object sourceFieldValue, ClassMap classMap, FieldMap fieldMapping) {
        //if field is initialized, Dozer will continue mapping
        return !Hibernate.isInitialized(sourceFieldValue));
    }
}
Ensoul answered 23/9, 2011 at 9:5 Comment(0)
S
4

Have you considered disabling lazy loading altogether?

It doesn't really seem to jive with the patterns you state you would like to use:

I would like to prevent Dozer from triggering lazy loading, so that hidden sql queries never occur : all fetching has to be done explicitly via HQL (to get the best control on performances).

This suggests you would never want to use lazy loading.

Dozer and the Hibernate-backed beans you pass to it are blissfully ignorant of each other; all Dozer knows is that it is accessing properties in the bean, and the Hibernate-backed bean is responding to calls to get() a lazy-loaded collection just as it would if you were accessing those properties yourself.

Any tricks to make Dozer aware of the Hibernate proxies in your beans or vice versa would, IMO, break down the layers of your app.

If you don't want any "hidden SQL queries" fired at unexpected times, simply disable lazy-loading.

Shows answered 5/4, 2011 at 13:15 Comment(5)
For sure, I would like to "disable lazy-loading" if it's possible, but how to do it ? I mean "default-lazy=false" means that all my associations will be eagerly fetched doesn't it ?Stolen
Yes, or you can specify lazy="false" on the class or property, and yes this will result in eager fetching. You have to have either eager fetching or lazy-loading; you can't map a property/collection with Hibernate and have it be loaded by Hibernate only some of the time.Shows
Ok, what I would like is : Hibernate never load my collections automatically when a getter is called. Hibernate loads my collections only when I specify it with an explicit "join" in an HQL query ("from Person join fetch Orders" for example) can you confirm this behavior is not possible with Hibernate ? (and is there some kind of reason...? or other popular frameworks which would fit this behavior ?)Stolen
Hibernate's philosophy is to return your object to you when you ask for it, including all collections (possibly lazy-loaded), associations etc. What you are describing is something a bit closer to the SQL layer, where you can have some control over what is fetched and what is not. You might be better off looking into other data-access libraries like iBatis SqlMaps which lets you map the results of queries (of your own specification) to objectsShows
Sorry Matt, there was a better answer (see down there).Stolen
Y
0

Short version of this mapper will be

return sourceFieldValue instanceof AbstractPersistentCollection && 
!( (AbstractPersistentCollection) sourceFieldValue ).wasInitialized();
Yolande answered 22/3, 2013 at 12:45 Comment(1)
I'm not sure how re-factoring the code to make it less readable really adds value to this answer.Kalahari
E
0

Using CustomFieldMapper may not be a good idea as it gonna invoke for every field of your source class,but our concern is only lazy association mapping(child object list),so we can set the null value in getter of the entity object,

public Set<childObject> getChild() {
if(Hibernate.isInitialized(child){
    return childObject;
}else
 return null;
}
Emendation answered 3/11, 2014 at 11:6 Comment(1)
This is effectively disabling lazy loading on all applicable collections though, not only for VO mapping. If you had any application internal logic that required the lazy loading of this collection, it would just get null. This question is specifically about disabling lazy loading for VO mapping, not altogether.Kalahari

© 2022 - 2024 — McMap. All rights reserved.