1

In my entities I have an object Shelf with a collection of books

public class Shelf{
  ...
  private List<Book> books;
}

In my ShelfDTO I only need to have the number of books

public class ShelfDTO{
  ...
  private int booksNumber;
}

I've tried with:

modelMapper.addMappings(new PropertyMap<Shelf, ShelfDTO>() {
        protected void configure() {
            map().setBooksNumber(source.getBooks().size());
        }
    });

But I got an exception when I try to start the app :

Caused by: java.lang.NullPointerException: null
    at org.modelmapper.internal.ExplicitMappingBuilder$ExplicitMappingInterceptor.access$000(ExplicitMappingBuilder.java:304) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.ExplicitMappingBuilder.createAccessorProxies(ExplicitMappingBuilder.java:287) ~[modelmapper-2.3.0.jar:na]
    at org.modelmapper.internal.ExplicitMappingBuilder.createProxies(ExplicitMappingBuilder.java:277) ~[modelmapper-2.3.0.jar:na]

Is there a way to do that with a property mapping or do I have to user a Converter?

Lempkin
  • 1,458
  • 2
  • 26
  • 49
  • 1
    `List books = new ArrayList<>();` can perhaps prevent `NullPointerException` – Karol Dowbecki Mar 18 '19 at 20:44
  • I tried but it didn't. not sure about where does the nullPointer comes from – Lempkin Mar 18 '19 at 20:46
  • If you are not going to immediately initialize your Arraylist when you make it, it'll be null until you define it. Where is your `books = new ArrayList<>();`? – FailingCoder Mar 18 '19 at 20:47
  • Are you by any chance mapping `TimeZone` object somewhere as explained in [this question](https://stackoverflow.com/questions/53287450/nullpointerexception-when-trying-to-define-a-custom-propertymap)? – Karol Dowbecki Mar 18 '19 at 20:50
  • @FailingCoder The list will contains books when I fetch the shelf from DB, if any. If not, list will be null, but even with a books = new ArrayList<>(); in the Shelf constructor, I still get same exception – Lempkin Mar 18 '19 at 20:50
  • @KarolDowbecki Nope, nothing like that – Lempkin Mar 18 '19 at 20:51
  • Forgot to mention (I've edited) but this exception happen when I try to run the app, not when the mapping occurs (as I cannot reach it obviously) – Lempkin Mar 18 '19 at 20:56
  • I think problem is not related to the attached code. Is this your only mapping? What happens when you comment those lines? NPE is thrown because o null interceptor in this case: https://github.com/modelmapper/modelmapper/blob/modelmapper-parent-2.3.0/core/src/main/java/org/modelmapper/internal/ExplicitMappingBuilder.java#L287 – glw Mar 18 '19 at 21:08

0 Answers0