我是MapStruct的新手,在Google上找不到我的问题的答案。
我有一个ShoppingCart,其中有Samples(以及其他属性),每个Sample需要一个引用返回我的ShoppingCart。是否可以使用MapStruct进行此类映射?
没有MapStruct,我只是将对ShoppingCart的引用传递给Samples。这是手写的:

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

最佳答案

您可以这样使用@AfterMapping批注:

@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);
        }
    }
}

关于java - MapStruct反向链接映射可能吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45483311/

10-11 10:49