2017-12-03 132 views
0

所以我有一個以下情況:更新實體通過ID使用瞬態的實例

我有擁有噸領域的客戶實體(20)。客戶 類看起來是這樣的(我剛上市前幾個字段):

@Entity 
public class Customer { 

    @Id 
    @GeneratedValue 
    private long id; 

    @Version 
    private version version; 

    private String firstName; 

    private String lastName; 

    private String email; 
    . 
    . 
    . 
} 

現在我應該通過接收它的所有更新客戶的方法是價值低谷RESTful Web服務。該服務方法看起來是這樣的:

@PUT 
@Path("{id}") 
@Consumes("application/json") 
@Produces("application/json") 
public Response editCustomer(@PathParam("id") long id, Customer customer) { 
    return FacadeUtils.buildResponse(updateCustomer(customer, id)); 
} 

而且我updateCustomer看起來是這樣的:

public Result updateCustomer(Customer customer, long id) { 
    @PersistenceContext 
    private EntityManager em; 

    customer.setId(id); 

    em.merge(customer); 
    . 
    . 
    . 
} 

然而,當我嘗試執行更新,我得到以下異常:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) 

我知道我可以通過使用oldCustomer = em.find(Customer.class, id);將對象加載到持久性上下文中,然後使用oldCustomer.setXXX(customer.getXXX);設置所需的所有值

但是,由於我有很多字段需要更新(有時候所有的20個字段都會更改,所以這樣做並不合適。

我知道我可以嘗試使用Reflections或Apache Bean Utils來複制字段,但必須有一些更優雅的解決方案。有任何想法嗎?

回答

0

我認爲這裏的主要問題是版本字段,您需要一個有效的版本值才能正確合併。您可以讓其餘的呼叫通過它以前收到的版本值。

相關問題