简体   繁体   English

SpringDataJPA @ManyToMany crud

[英]SpringDataJPA @ManyToMany crud

I want to insert a goods我要插入商品

with or without some categories already in database.数据库中有或没有某些类别。

I have seen many similar problems and solution,seem like CascadeType ?我见过很多类似的问题和解决方案,好像是CascadeType

Actually I don't figure out.其实我不明白。

here are two class and test这里有两个 class 和测试

@Entity
@Table(name = "t_goods")
@Data
public class Goods implements Serializable {
    private static final long serialVersionUID = -7781710173608724249L;
    @Id
    @GenericGenerator(name = "goodsid",strategy = "uuid")
    @GeneratedValue(generator = "goodsid")
    private String goodsId;

    private String goodsName;

    @ManyToMany(cascade = {CascadeType.PERSIST})
    private Set<GoodsCate> goodsCateSet;
}

@Entity
@Table(name = "t_category",uniqueConstraints = { @UniqueConstraint(columnNames = "cateName")})
@Getter
@Setter
public class GoodsCate implements Serializable {
    private static final long serialVersionUID = -8990216455436375344L;
    @Id
    @GenericGenerator(name = "goodscateid",strategy = "uuid")
    @GeneratedValue(generator = "goodscateid")
    private String cateId;

    private String cateName;

   @ManyToMany(mappedBy = "goodsCateSet")
   private Set<Goods> goods;
}

@Test
void test(){

    Goods goods = new Goods();
    goods.setGoodsName("apple");

    GoodsCate food = new GoodsCate();
    food.setCateName("food");
    GoodsCate fooddb= goodsCateRepo.findGoodsCateByCateName(food.getCateName());
    if(fooddb!=null){
        food=fooddb;
    }
    GoodsCate vegetable= new GoodsCate();
    vegetable.setCateName("vegetable");
    GoodsCate vegetabledb = goodsCateRepo.findGoodsCateByCateName(vegetable.getCateName());
    if(vegetabledb!=null){
        vegetable = vegetabledb;
    }
    Set<GoodsCate> goodsCates = Sets.newSet(food, vegetable);


     goods.set(goodsCates);
     // goodsRepo is a interface extends jpaReposity
     goodsRepo.save(goods);

}

it throws它抛出

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist:com.xx.xxx.GoodsCate org.springframework.dao.InvalidDataAccessApiUsageException:分离的实体传递给坚持:com.xx.xxx.GoodsCate

It looks like you haven't linked your category to goods.您似乎没有将您的类别与商品相关联。

I would suggest to add two utility methods (eg addCategory(Category category) in Goods and addGood(Goods good) in Category) which are used to synchronize both sides of the bidirectional association.我建议添加两个实用方法(例如,在 Goods 中添加addCategory(Category category) ,在 Category 中添加addGood(Goods good) ),用于同步双向关联的双方。 You should always provide these methods whenever you are working with a bidirectional association as, otherwise, you risk very subtle state propagation issues.当您使用双向关联时,您应该始终提供这些方法,否则,您将面临非常微妙的 state 传播问题。

In GoodsGoods

public void addCategory(Category category) {
        categories.add(category);
        category.getGoods().add(this);
    }

In CategoryCategory

public void addGood(Good good) {
        goods.add(good);
        good.getCategory().add(this);
    }

Note : Also don't forget to add remove utility just like above one. Note :也不要忘记像上面一样添加remove实用程序。

Then you can use below code然后你可以使用下面的代码

@Test
    void test(){

        Goods goods = new Goods();
        goods.setGoodsName("apple");

        GoodsCate food = new GoodsCate();
        food.setCateName("food");
        GoodsCate fooddb= goodsCateRepo.findGoodsCateByCateName(food.getCateName());
        if(fooddb!=null){
            food=fooddb;
        }
        GoodsCate vegetable= new GoodsCate();
        vegetable.setCateName("vegetable");
        GoodsCate vegetabledb = goodsCateRepo.findGoodsCateByCateName(vegetable.getCateName());
        if(vegetabledb!=null){
            vegetable = vegetabledb;
        } 
        //********After adding mentioned utilites********    
         goods.addCategory(food);
         goods.addCategory(vegetable);
         // goodsRepo is a interface extends jpaReposity
         goodsRepo.save(goods);

    }

One of the article for Many to Many best practices 多对多最佳实践的文章之一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM