Search code examples
javadtodozer

How to specify limit or level of recursion of a circular relationship using Dozer


I have two JPA2 entity classes that refer to each other

class Person {
   int id;
   String name;
   @ManyToOne(fetch = FetchType.LAZY)
   Company company;
}

class Company{
   int id;
   String name;
   @ManyToOne(fetch = FetchType.LAZY)
   Person representative;
}

Having this data:

Company company1 = Company(1,"Company1", 2)
Company company2 = Company(2,"Company2", 1)

Person person1 = Person (1,"Person1", 1)
Person person2 = Person (2,"Person2", 2)

person2 works for company2, whose representative is person1 which works for company1 whose representative is once again person2

I know that Dozer is capable of copying this model to DTO's (CompanyDTO and PersonDTO). In my tests, they work and have infinite levels of recursion. I understand this is because Dozer uses the same instantiated objects as references in the DTO's.

My question is, what if there were thousands of persons who represent hundreds of companies, couldn't the graph of a PersonDTO instance be too large to handle? How can I specify some sort of limit for this situation?


Solution

  • There are two possible strategies to handle this situation.

    1. Before invoking Dozer loop through your data model to trigger lazy loading until the depth you need. Then use proxy handling feature of Dozer, so it would unwrap the object and do not trigger lazy loading any further (http://dozer.sourceforge.net/documentation/proxyhandling.html). There is a proxy handler for Hibernate, if you are using Eclipse Link or something else you have to write your own.
    2. Write a custom converter (http://dozer.sourceforge.net/documentation/customconverter.html), which would traverse the object hierarchy until the level you need. It could be done with MapperAware recursive custom converter or plain converter using ThreadLocal as a level counter.