如何删除JPA @ManyToMany关系中的记录?

时间:2014-02-07 07:01:22

标签: java sql jpa many-to-many openjpa

我定义了一个单向的ManyToMany关系,如下所示:

@Entity
@Table(name = "ODE_PROCESS_INSTANCE")
Public class ProcessInstanceDAOImpl extends OpenJPADAO implements ProcessInstanceDAO {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long _instanceId;

  @ManyToMany(targetEntity = PolicyAttachmentDAOImpl.class)
  private Collection<PolicyAttachmentDAO> _policyAttachments = new ArrayList<PolicyAttachmentDAO>();

  public ProcessInstanceDAOImpl() {
  }

  public Collection<PolicyAttachmentDAO> getPolicyAttachments(){
    return _policyAttachments;
  }

  public void setPolicyAttachments(Collection<PolicyAttachmentDAO> policyAttachments){
    _policyAttachments = policyAttachments;
    getEM().merge(this);
    getEM().flush();
  }
}

@Entity
@Table(name = "ODE_POLICY_ATTACHMENT")
public class PolicyAttachmentDAOImpl extends OpenJPADAO implements PolicyAttachmentDAO{
  @Id
  @Column(name = "POLICYATTACHMENT_ID")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long _attachmentId;

  @Basic
  @Column(name = "POLICYATTACHMENT_NAME")
  private String _attachmentName;

  public PolicyAttachmentDAOImpl(String policyAttachmentName) {
    _attachmentName = policyAttachmentName;
  }

  public void deletePolicyAttachment(){
    //delete policy attachment DAO
getEM().remove(this);
getEM().flush();
  }
}

创建了连接表。问题是当我从ODE_POLICY_ATTACHMENT删除记录时,连接表不会更新。我该如何解决这个问题?

这是我添加到ta

的方式
Collection<PolicyAttachmentDAO> policyAttachments = new ArrayList<PolicyAttachmentDAO>();

attachmentDAO = new PolicyAttachmentDAOImpl("attachment_1");
policyAttachments.add(attachmentDAO);

attachmentDAO = new PolicyAttachmentDAOImpl("attachment_2");
policyAttachments.add(attachmentDAO);

attachmentDAO = new PolicyAttachmentDAOImpl("attachment_3");
policyAttachments.add(attachmentDAO);

//inst is an exisiting ProcessInstanceDAOImpl
inst.setPolicyAttachments(policyAttachments);

从&#34; ODE_PROCESS_INSTANCE&#34;删除记录table我在PolicyAttachmentDAOImpl对象上调用deletePolicyAttachment()方法。

1 个答案:

答案 0 :(得分:1)

连接表是映射多对多关联的内容。这是允许Hibernate知道某些附件与某个进程相关联的原因。因此,如果您不希望在连接表中引用附件,则意味着您不希望附件再次链接到任何进程。所以答案很简单:在集合中找到所有具有附件的进程,并从其集合中删除附件:

process.getPolicyAttachments().remove(theAttachment);

旁注:你的命名很糟糕。在字段前加下划线不是标准惯例,并会强制您在所有查询中添加此前导下划线。而你所拥有的不是DAO,而是实体。 DAO是用于查询和更新数据库的对象。实体是DAO返回的持久对象。每次更改进程的附件时都不应合并和刷新。合并很少是必要的,而且几乎从不冲洗,这不应该由一个实体来完成,它根本不应该访问EM。