gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:30:05 26 4
gpt4 key购买 nike

我定义了一个单向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);

要从“ODE_PROCESS_INSTANCE”表中删除记录,我在 PolicyAttachmentDAOImpl 对象上调用方法 deletePolicyAttachment()。

最佳答案

连接表用于映射多对多关联。它让 Hibernate 知道某些附件与某些进程相关联。因此,如果您不希望在连接表中引用附件,则意味着您不再希望该附件链接到任何进程。所以答案很简单:找到其集合中包含附件的所有进程,并从其集合中删除附件:

process.getPolicyAttachments().remove(theAttachment);

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

关于java - 如何删除JPA @ManyToMany关系中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21621283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com