Search code examples
hibernatehashmapdozer

Dozer: Hibernate PersistentMap is not mapped to java.util.HashMap


I have a Hibernate annotated entity with a field:

@OneToMany(mappedBy="templateInstance", fetch = FetchType.EAGER) 
@MapKey(name = "attributeName") 
private Map<String, Component> components; 

Hibernate makes a PersistentMap out of this. Then I want Dozer to map this to an object with such a field:

private Map<String, ComponentDto> components; 

After having LazyInitializationExceptions and some debugging, I found out, that it´s not a problem of a closed Hibernate session, but that Dozer tries not to map to a HashMap but to a PersistentMap! And therefore when Dozer accesses the target map the PersistentMap throws the Exception, because it has no session of course.

So, I thought that the intented behaviour of Dozer is to map to a HashMap. Now the question: am I doing something wrong or Dozer and how can I get Dozer to map the PersistentMap to normal Java standard map?

I had no problems when using a List before. Has anybody else used Dozer for mapping Hibernate PersistentMap?

Regards, Konsumierer


Solution

  • I found the solution by myself. The components field in the DTO has to look like this:

    HashMap<String, Component> components = new HashMap<String, Component>;
    

    Only this way you can prevent Dozer from using the PersistentMap as the target object.

    And the other important thing is to use a custom BeanMappingBuilder for the DO that holds the map and that looks like that:

    public class TemplateInstanceMappingBuilder extends BeanMappingBuilder {
    
        @Override
        protected void configure() {
    
            mapping(TemplateInstance.class, TemplateInstanceDto.class)
                .fields("components", "components", FieldsMappingOptions.hintB(ComponentDto.class));
    
        }
    }
    

    For further information about that problem, see the Dozer forums at https://sourceforge.net/projects/dozer/forums/forum/452530/topic/4020856/index/page/1