79673796

Date: 2025-06-20 18:07:12
Score: 0.5
Natty:
Report link

A little late here but here's a solution for posterity:

You can get MapStruct to add a collection using an adder of individual elements rather than the setter of the entire list using the CollectionMappingStrategy.ADDER_PREFERRED .

@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface AuthorMapper {

   @Mapping(target = "authorName", source = "request.authorRequestName")
   @Mapping(target = "authorBooks", source = "request.authorRequestBooks")
   Author map(AuthorRequest request);

   // You'd still need to explain how to map an individual book
   // This can be done in a separate Mapper as well
   public Book map(String bookTitle);
}

Then modify your entity to use adders to add to the list. Here you can reference the parent Author and the child Book as they are being mapped and create a relation.

@Entity
class Author {
   
   @Id
   private Long id;
   
   private String authorName;
   
   @OneToMany(mappedBy = "author")
   private List<Book> authorBooks;

   public void addBook(Book book) {
      authorBooks.add(book);
      book.setAuthor(this);
   }
}

This is what the book mapping part of the generated code will look like:

public class AuthorMapperImpl implements AuthorMapper {
   ...
   
   public Author map(AuthorRequest request) {

      Author author = new Author();
      author.setAuthorName(request.getAuthorRequestName());
      if (request.getAuthorRequestBooks() != null) {
         for ( String bookTitle : request.getAuthorRequestBooks() ) {
            author.addBook( map( bookTitle ) );
         }
      }

      return author;
   }
 
   ...
}

This is especially useful when you're dealing with JPA relations like @OneToMany where you need the child as the owner of the relation to point back to the parent object, so you need the add method anyway.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @OneToMany
  • Low reputation (1):
Posted by: PrawDG