Mapping @ManyToMany collection to collection of ids

Viewed 327

I'm trying to map a JPA entity (Recipe) containing a collection of different Products with a many-to-many association.

@Data
public class Recipe {
    private String id;
    //ManyToMany
    private Set<Product> products;
}
@Data
public class Product {
    private String id;
    private String name;
    //ManyToMany
    private Set<Recipe> recipes;
}

For the result, I'm only interested in the ids of those entities:

@Data
public class RecipeDTO {
    private String id;
    private Set<String> productIds;
}

So that leads to this mapper:

@Mapper
public interface RecipeMapper {
    @Mapping(target = "productIds", source = "products.id")
    RecipeDTO mapToDto(Recipe recipe);
}

Now, this doesn't work:

RecipeMapper.java:8: error: No property named "products.id" exists in source parameter(s). Did you mean "products.empty"?
    @Mapping(target = "productIds", source = "products.id")
                                             ^

Too bad. I was hoping to make it work like this, but it makes sense that it doesn't work. My next idea was to define a method to map a Product to a String, extracting its id, possibly @Named. Using something like String mapToProductId(Product product), but the @Mapping annotation needs a target, which in this case would be the String (value) itself. I'm not sure if this is at all possible, I've looked at the documentation, the examples, the user group, and Stackoverflow, to no avail.

So, at this point, it would be easier to implement the whole mapping of Recipe myself, but I can't help but feel like I'm missing something. Is there a better way to do this?

1 Answers

I suppose you need to implementString mapToProductId(Product product) and change "products.id " to "products" like:

@Mapper
public interface RecipeMapper {
    @Mapping(target = "productIds", source = "products")
    RecipeDTO mapToDto(Recipe recipe);

    default String mapToProductId(Product product) {
      return product.getId();
    }
}
Related