5

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.

Peter Kipping
  • 623
  • 6
  • 12

1 Answers1

3

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

Filip
  • 19,269
  • 7
  • 51
  • 60
  • I agree it is a bit manual. However, if you have some idea how it can be improved you can create an issue [here](https://github.com/mapstruct/mapstruct/issues/) – Filip Feb 10 '17 at 17:35
  • I've tested something similar on `1.1.0.Final` but looks like it doesn't work. – cassiomolin May 25 '17 at 00:30
  • Can you elaborate what exactly doesn't work? What do you have? If you think that it is a bug please open an issue on [github](https://github.com/mapstruct/mapstruct/issues), if it is not the same as this question maybe a new one is needed – Filip May 25 '17 at 08:58
  • Is there any way to @Mapper multiple times (for many lazy loaded fields)? – Houssam Badri Apr 08 '19 at 11:30
  • If you are using lazy loading, it's worth looking at this answer https://stackoverflow.com/questions/53465814/lazy-loading-not-working-in-jpa-with-hibernate/56568692#56568692 – Vishrant Jun 12 '19 at 19:02