更新实体通过ID使用瞬态的实例

更新实体通过ID使用瞬态的实例

问题描述:

所以我有一个以下情况:更新实体通过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来复制字段,但必须有一些更优雅的解决方案。有任何想法吗?

我认为这里的主要问题是版本字段,您需要一个有效的版本值才能正确合并。您可以让其余的呼叫通过它以前收到的版本值。