2016-06-22 149 views
0

之前如何刷新關係我想刪除與另一個的@OneToMany關係的實體,成立這樣的:刪除實體

public class Dealership implements Serializable { 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "dealership", orphanRemoval = true) 
    private Set<Car> cars; 
} 

public class Car implements Serializable { 

    @ManyToOne 
    @JoinColumn(name="co_id") 
    private Dealership dealership; 

} 

的事情是,當我刪除了經銷店,我只想刪除未售出的汽車。無論我嘗試什麼,Hibernate都會通過級聯刪除與經銷商並列的所有汽車。這是我一直在嘗試的。在這個例子中,我試圖將售出的汽車轉移到另一個經銷商,然後我刪除經銷商。這應該刪除經銷商,其僱員,並且只有未售出的汽車:

Session session = SessionManager.getSession(); 
Transaction tx = session.beginTransaction(); 

Dealership dealershipToDelete = (Dealership) session.load(Dealership.class, idDealership); 

for(Car c: dealershipToDelete.getCars().stream().filter(c -> c.isSold()).toArray(Car[]::new)){ 
    Dealership newDealership = (Dealership) session.load(Dealership.class, idNewDealership); 
    c.setDealership(newDealership); 
    dealershipToDelete.getCars().remove(c); 
} 

session.update(dealershipToDelete); 

session.flush(); 

session.delete(dealershipToDelete); 

tx.commit(); 

session.close(); 

但它總是刪除所有汽車。即使我設法讓Hibernate用新的經銷商來更新汽車。它更新它們,然後刪除它們。幫助將不勝感激。謝謝。

+0

你並沒有將汽車添加到新的經銷商。你不會從他們的舊經銷商那裏取出汽車。 –

+0

對不起,我忘了添加從舊經銷商刪除汽車的線。我在發佈之前已經測試過它。它仍然不起作用。 現在我沒有把它添加到新的關係。但現在,我加入這一行環路(在它的結束): 'newDealership.getCars()加(C);' 它拋出這個異常: 異常線程「main」組織。 hibernate.ObjectDeletedException:刪除的對象將被級聯重新保存(從關聯中刪除刪除的對象):[hibernate.entities.Car#14] – MatiasP

+0

@MatiasMGS是你的問題解決? –

回答

1

刪除它,以反映其與汽車class.Have關係所做的更改稍加修改你的代碼之前就刷新()經銷店的對象,試試這個:

Dealership dealershipToDelete = (Dealership) session.load(Dealership.class, idDealership); 
Dealership newDealership = (Dealership) session.load(Dealership.class, idNewDealership); 
for(Car c: dealershipToDelete.getCars().stream().filter(c -> c.isSold()).toArray(Car[]::new)){ 
    c.setDealership(newDealership); 
    newDealership.getCars().add(c); 
} 
session.flush(); //this will flush the updates to sold Car, with the new Dealership details 
session.refresh(dealershipToDelete); //this will load the updated "dealershipToDelete" without the 'Sold Car' object,the 'Unsold' ones will still be there 
session.delete(dealershipToDelete); //this will delete the Dealership and its related unsold car objects. 

tx.commit(); 

session.close(); 
1

,你可以嘗試這樣的事:

首先將外鍵可空:

public class Car implements Serializable { 

    @ManyToOne 
    @JoinColumn(name="co_id" , nullable = true) 
    private Dealership dealership; 

} 

那麼你得到dealershipToRemove的Id:

int id = dealershipToRemove.getId(); 

然後刪除所有汽車與代理商一樣具有經銷商

query = session.createNativeQuery("delete from cars where co_id = :id and date is null"); 
query.setParameter(1,id); 
query.executeUpdate(); 

然後你打破dealershipToRemove和汽車之間的關係:

dealershipToRemove .setCars(null); 
session.remove(dealershipToRemove); 
+0

難道不是所有的汽車都會被拆除嗎?因此'session.remove(dealershipToRemove)'會和所有這些產生完全相同的效果。爲查詢添加'「和日期爲空」'會修復它,但我正在尋找更多的解決方案,使用休眠而不是查詢,如SB的答案。 – MatiasP

+0

是你的權利! (y)的 –