删除OneToMany关系中的实体 [英] remove an entity in OneToMany relationship

查看:94
本文介绍了删除OneToMany关系中的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解在从OneToMany关系中移除一个实体时需要付出的最小努力。我发现很多例子只是将实体添加到这些集合中(并且完全正确),但删除实体更加困难。

I have trouble understanding what minimal effort is needed on my part in removing an Entity from a OneToMany relationship. I find a lot of examples just adding Entities to these sets (and that works out allright), but removing entities is much more difficult to find.

我有以下类:

I have the following class:

@Entity
public class Product {
    ... 
    OneToMany(mappedBy="product", orphanRemoval=true,
              cascade={CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},fetch=FetchType.EAGER)
    Set<Expert> experts = new HashSet<Expert>();
    ...
}

@Entity
public class Expert {
    ...
    @ManyToOne(optional=false)
    Product product;

    @ManyToOne(optional=false)
    Person person;

    ...
}

(Person类似于产品)

(Person is similar to Product)

我拥有充满产品和专家的产品。我想从产品列表中删除专家,以便专家实体完全删除。我预计下面的代码就足够了:

I have it filled with Products and experts. I want to remove an expert from the list of products so the expert entity is removed completely. I would expect that either the following code would be enough:

Product aProduct = findAProduct(...);
Expert anExpert aProduct.getExperts.get(...); // Just get the first expert that I want removed
EntityManager em = entityManager();

  em.getTransaction().begin();
  aProduct.getExperts().remove(anExpert);
  em.merge(aProduct);
  em.getTransaction().commit();

或:

or:

  em.getTransaction().begin();
  em.remove(anExpert);
  em.getTransaction().commit();

这是否过于简单? JPA做了什么,我该做什么?我之前通过使用查询解决了这个问题,但我希望JPA能为我做到这一点。

Is this too simplistic? What is done by JPA and what do I have to do myself? I have solved it before by just using queries but I expect that JPA can do this for me.

推荐答案

EntityManager em = entityManager();
// Retrieve the expert in the new EntityManager context 
Expert expertToDelete = em.find(Expert.class, anExpert.id);

em.getTransaction().begin();
expertToDelete.getProduct().getExperts().remove(expertToDelete);
expertToDelete.getPerson().getExperts().remove(expertToDelete);
em.remove(expertToDelete);
em.getTransaction().commit();

它可能很好地代替了通过find找回专家,您可以使用merge )而不是上面的,但上面的工作似乎有效。

It could very well be that instead of retrieving the expert via the find, you can use a merge() on anExpert instead, but the above seems to work.

这篇关于删除OneToMany关系中的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆