MapStruct backlink mapping possible?

gute Fee

I am new to MapStruct and could not find an answer to my question on google. I am having a ShoppingCart which has got Samples (among other properties) and each Sample needs a reference back to my ShoppingCart. Is it possible to do such mapping with MapStruct? Without MapStruct I simply pass a reference to the ShoppingCart to the Samples. This was written by hand:

protected ShoppingCart map(Cart cart, DataShareOption dataShareOption) {
//(other stuff)
   for (CartSample cartSample : cart.getCartSamples()) {
       ShoppingCartSample sample = mapCartSample(cartSample, shoppingCart,
       dataShareOption);
       shoppingCart.getSamples().add(sample);
   }
}

protected ShoppingCartSample mapCartSample(CartSample cartSample,
    ShoppingCart shoppingCart, DataShareOption dataShareOption) {

     ShoppingCartSample sample = new ShoppingCartSample();
     sample.setShoppingCart(shoppingCart);
     //(other stuff)
     return sample;
}

// the classes declarations:
// business class
public class ShoppingCart extends ShoppingCartHeader
{
    private List<ShoppingCartSample> samples = new   ArrayList<ShoppingCartSample>();
//rest of the class


// data base class:
@Entity
@Table(name = "cart")
public class Cart extends BaseEntity
{
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "cart")
private Set<CartSample> cartSamples = new HashSet<CartSample>();
   // more stuff here


// business class:
  public class ShoppingCartSample
  {
   private ShoppingCart shoppingCart;
  // rest of the class


// data base class:
@Entity
@Table(name = "cart_sample")
public class CartSample
{
   @ManyToOne()
   @JoinColumn(name = "cart_id")
   private Cart cart;
   // more stuff here
Tomer Gal

You can use the @AfterMapping annotation like so:

@Mapper
public interface ShoppingCartMapper{
    ShoppingCart map(Cart cart);
    ShoppingCartSample map(CartSample cartSample);

    @AfterMapping
    default void setShoppingCartSampleParent(@MappingTarget ShoppingCart cart){
        for(ShoppingCartSample cartSample : cart.getSamples()){
            cartSample.setShoppingCart(cart);
        }
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related