Search code examples
hibernatemapstruct

Can MapStruct do a deep deproxy of Hibernate Entity Classes


This is a common issue for web service developers who would like to return entity classes directly. Even if all the data I need is loaded there are still many uninitialized proxies and collections that I don't need. I would like for them to just return null and not throw a Lazy Load Exception. Basically I just want the POJO contract, however proxies and hibernate collections have to be purged to get that (unless there is some new way in hibernate that I don't know about). Can I use MapStruct to do this?

More details about this if needed:

http://www.mojavelinux.com/blog/archives/2006/06/hibernate_get_out_of_my_pojo/

http://www.gwtproject.org/articles/using_gwt_with_hibernate.html

Gilead was the only thing that I found that worked well for this but it is no longer around.


Solution

  • Yes you can do that with MapStruct. However, only by explicitly marking what you want to map and what you want to ignore.

    Let's say you have this classes:

    public class Car {
    
        private String name;
        private int year;
        //This is lazy loaded
        private List<Wheel> wheels;
        //getters and setters omitted for simplicity
    }
    
    public class Wheel {
        private boolean front;
        private boolean right;
        //getters and setters omitted for simplicity
    }
    

    You will need a mapper that looks like this:

    @Mapper
    public interface CarMapper {
    
        @Mapping(target="wheels", ignore=true)
        Car mapWithoutWheels(Car car);
    
        Car mapWithWheels(Car car);
    
        List<Wheel> map(List<Wheel> wheels);
    
        Wheel map(Wheel wheel);
    }
    

    The explicit mapping for List<Wheel> and Wheel is needed if you want to force MapStruct to create new objects and not do direct mapping. Currently, if MapStruct sees that the source and target type are same it does direct assignment (with lists it will create a new list, but it won't call getters in the elements of the list).

    If Wheel had some lazy loaded elements, then you can have 2 methods for mapping Wheel and you will have to use selection based on qualifiers