Java 如何从集合中正确级联删除实体?
我试图在两个Hibernate实体之间使用联接表使多对一关系顺利工作,但在级联从“一”端集合中删除实体时遇到了问题 在下面的代码片段中,我省略了简单的getter/setter 代码 一方实体表示数据库中的FTP_服务器:Java 如何从集合中正确级联删除实体?,java,hibernate,jpa,orm,Java,Hibernate,Jpa,Orm,我试图在两个Hibernate实体之间使用联接表使多对一关系顺利工作,但在级联从“一”端集合中删除实体时遇到了问题 在下面的代码片段中,我省略了简单的getter/setter 代码 一方实体表示数据库中的FTP_服务器: @Entity @Table(name = "ftp_server") public class FtpServerEntity { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationTy
@Entity
@Table(name = "ftp_server")
public class FtpServerEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "ftpServer", cascade = CascadeType.ALL)
@Fetch(FetchMode.JOIN)
private List<SmtpRecipientEntity> smtpRecipients;
}
@Entity
@Table(name = "smtp_recipient")
public class SmtpRecipientEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(
name = "ftp_error_recipient",
joinColumns = @JoinColumn(name = "smtp_recipient_id"),
inverseJoinColumns = @JoinColumn(name = "ftp_server_id")
)
private FtpServerEntity ftpServer;
}
FOREIGN KEY (smtp_recipient_id) REFERENCES smtp_recipient (id)
FOREIGN KEY (ftp_server_id) REFERENCES ftp_server (id)
并且联接表只有以下外键:
@Entity
@Table(name = "ftp_server")
public class FtpServerEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "ftpServer", cascade = CascadeType.ALL)
@Fetch(FetchMode.JOIN)
private List<SmtpRecipientEntity> smtpRecipients;
}
@Entity
@Table(name = "smtp_recipient")
public class SmtpRecipientEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(
name = "ftp_error_recipient",
joinColumns = @JoinColumn(name = "smtp_recipient_id"),
inverseJoinColumns = @JoinColumn(name = "ftp_server_id")
)
private FtpServerEntity ftpServer;
}
FOREIGN KEY (smtp_recipient_id) REFERENCES smtp_recipient (id)
FOREIGN KEY (ftp_server_id) REFERENCES ftp_server (id)
问题
只需向FtpServerEntity#smtpRecipients集合添加一个SMTPrecipienty即可,更新后会在联接表中创建一行
但是,当我修改集合,然后持久化FtpServerEntity时,删除的记录不会从联接表中删除
即
//它的集合中有三个SMTPrecipientity对象
FtpServerEntity ftpServer=ftpServerDao.get(ftpServerId);
List recipients=ftpServer.getSmtpRecipients();
收件人。清除();
add(smtpRecipientDao.get(smtpRecipientId));
//集合中现在只有一个不同的实体
ftpServerDao.save(ftpServer);//执行合并和刷新
此代码将为添加到集合中的实体向联接表添加新记录,但不会删除不再在集合中的实体的记录。我可以通过几种不同的方式手动完成这项工作,但这感觉就像Hibernate应该能够处理的一样
你知道我遗漏了什么吗?感谢您提供的所有帮助。除了您的
级联之外,尝试添加孤儿删除=true
。所有,这样子元素将在不再从所有者引用时被删除