Prevent Dozer from triggering Hibernate lazy loading

14,965

Solution 1

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.

Solution 2

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;
}

}

Solution 3

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));
    }
}

Solution 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.

Share:
14,965

Related videos on Youtube

Tristan
Author by

Tristan

Updated on February 06, 2020

Comments

  • Tristan
    Tristan almost 4 years

    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.

  • Tristan
    Tristan over 12 years
    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 ?
  • matt b
    matt b over 12 years
    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.
  • Tristan
    Tristan over 12 years
    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 ?)
  • matt b
    matt b over 12 years
    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 objects
  • Tristan
    Tristan over 12 years
    Thanks, this is great, I can even confirme it is not documented anywhere else than here : google.fr/search?q=CustomFieldMapper+PersistentSet
  • Tristan
    Tristan over 12 years
    Sorry Matt, there was a better answer (see down there).
  • Tristan
    Tristan over 12 years
    Also, in a recent version of Dozer (5.3.0), there is an other way to do it (sourceforge.net/tracker/…)
  • JamieB
    JamieB over 9 years
    I'm not sure how re-factoring the code to make it less readable really adds value to this answer.
  • JamieB
    JamieB over 6 years
    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.