2015-02-06 78 views
0

我想通過一個連接表來獲得兩個Hibernate實體之間的多對一關係,但我在從「one」側集合中級聯刪除一個實體時遇到了問題。如何正確級聯刪除集合中的實體?

我在下面的代碼片段中省略了簡單的getters/setters。

「一」 側實體表示數據庫中的FTP_SERVER的代碼:

@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; 

} 

「多」(和擁有)側實體代表一個SMTP_RECIPIENT:

@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) 

的問題

只需添加SmtpRecipientEntity到FtpServerEntity#smtpRecipients收集工作正常,並連續在連接表時更新創建。

但是,當我修改集合,然後保留FtpServerEntity時,刪除的記錄不會從連接表中刪除。

I.E.

// This has three SmtpRecipientEntity objects in its collection 
FtpServerEntity ftpServer = ftpServerDao.get(ftpServerId); 

List<SmtpRecipientEntity> recipients = ftpServer.getSmtpRecipients(); 
recipients.clear(); 
recipients.add(smtpRecipientDao.get(smtpRecipientId)); 

// The collection now has only one different entity in it 
ftpServerDao.save(ftpServer); // performs a merge and flush 

此代碼將添加一個新的記錄的連接表爲實體添加到集合,但不刪除記錄是集合中不再的人。我可以通過幾種不同的方式手動執行此操作,但這感覺像Hibernate應該能夠處理的。

關於我失蹤的任何想法?感謝任何和所有的幫助。

回答

0

嘗試在Cascade.ALL之外添加orphanRemoval = true,以便在不再引用所有者時子元素將被刪除。