2017-01-23 40 views
0

按我的要求,我一直在使用,我想用下面的代碼標識被改變

更新/重新分配經理到客戶的客戶和經理

class CustomerEntity{ 

    @ManyToOne 
    @JoinColumn(name = "manager_id", referencedColumnName = "id") 
    private ManagerEntity manager; 

} 

class ManagerEntity{ 

     @OneToMany(mappedBy = "manager", fetch = FetchType.LAZY) 
     private List<CustomerEntity> customerlist; 

} 

現在之間JPA創建多對一關係

public void updateManager(Customer customer) throws Exception { 
    CustomerEntity customerEntity = customerDao.find(customer.getId()); 
    ManagerEntity managerEntity = userDao.find(customer.getManagerId()); 
    customerEntity.setManager(managerEntity); 
    getSession().update(entity); 
} 

但同時節省我得到以下

提到的異常產生的原因:org.hibernate.HibernateExcepti on:ManagerEntity的一個實例的標識符從10改爲15

根據例外情況,我可以理解它試圖更新ManagerEntity中的行,即子表,但我不想在ManagerEntity中進行任何更新,只有任何現有ManagerEntity應重新分配給CustomerEntity。

我試圖在CustomerEntity中提供CascadeType.MERGE或CascadeType.DETACH,但它不起作用。

任何人都可以給我建議正確的方法,而無需更新ManagerEntity即子實體更新CustomerEntity實體即父

+0

你做** customerEntity.getManager()的setName( 「新名字」)**客戶應具備的經理,所以你don'。不得不從DB中檢索。在我看來,您正在更新的經理實體與客戶的經歷並不一樣,並且休眠抱怨 – kimy82

+0

爲什麼要單獨獲取ManagerEntity?當你獲取CustomerEntity時,它也應該獲取管理器。因此不需要在客戶實體中設置經理。將獲取類型更改爲渴望並查看您的代碼是否與客戶一起獲取經理。 –

+0

它看起來是正確的,除非你在.setManager方法中做了一些奇怪的事情,你能顯示代碼嗎? – jorgegm

回答

0

我會建議你做一個保存更新級聯

  1. 助理你的孩子保存更新級聯

  2. 取父

  3. 更新子實體

  4. 做一個saveOrUpdate

參考: - http://javaforloop.com/hibernate/hibernate-cascade-inverse-example-none-save-update-delete-delete-orphan/

我建議你通過管理者的ID被更新作爲單獨的參數

public void updateManager(Customer customer , Long managerId) throws Exception { 

//Below code will fetch the customer you need to update 
    CustomerEntity customerEntity = customerDao.find(customer.getId()); 
    ManagerEntity managerEntity = new ManagerEntity(); 
    managerEntity.setId(managerId); 
    customerEntity.setManager(managerEntity); 
    getSession().saveOrUpdate(customerEntity); 
} 
+0

我嘗試使用 getSession()。evict(managerEntity)驅逐managerEntity; 它保存了CustomerEntity,但ManagerEntity沒有保存,這是顯而易見的。你能建議保存經理實體的方式嗎? – Ketan

+0

我不知道你想更新客戶而不是經理。如果你想更新子實體,你需要級聯它。 –

+0

對不起Saket。我錯打了問題。我根本不想保存ManagerEntity。您可以在更新家長時不要更新孩子,我不想更新孩子實體。 再次抱歉我的錯誤評論上面。 – Ketan

0

我做了一個小測試,並得到與此代碼相同的例外:

void setManager(ManagerEntity managerEntity) { 
    this.manager.setId(managerEntity.getId()); 
} 

,而不是正確的:爲什麼鴕鳥政策

void setManager(ManagerEntity managerEntity) { 
    this.manager = managerEntity; 
}