2016-12-15 132 views
0

如果我有这样的JPA - 更新童车refrence于母公司

public class Company implements Serializable { 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name="COMPANY_ID", updatable = false) 
private int companyId; 

//bi-directional many-to-one association to User 
@OneToMany(mappedBy="company") 
private List<User> users; 
} 

父母,这样

public class User implements Serializable { 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name="USER_ID", updatable=false) 
private int userId; 

private String username; 

//bi-directional many-to-one association to Company 
@ManyToOne 
@JoinColumn(name="COMPANY_ID") 
private Company company; 
} 

然后在我的JAX-RS REST孩子叫我从检索用户公司A中的数据库,我想将该用户更改为公司B.下面是我所拥有的

@POST 
@Path("updateUserCompany") 
@Produces("application/json") 
public Response updateUserCompany() { 

    //this get the company I want to set the user to 
    Company company = entityManager.createNamedQuery("Company.getCompanyByName", Company.class) 
       .setParameter("companyName", "CompanyB") 
       .getSingleResult(); 

    //this gets the user i want to change 
    User user = entityManager.createNamedQuery("User.getUserById", User.class).setParameter("userId", 1).getSingleResult(); 

    user.setCompany(company); 
    entityManager.persist(user); 
    entityManager.flush(); 

但是用户没有更新D B?我如何在数据库中更新它?

感谢

+0

1)您的JAX-RS REST类EJB是什么?因为如果这个代码不是在内部交易中执行的话。用'javax.transaction.Transactional'注释'updateUserCompany()'方法。 2)使用'entityManager.merge()'方法,而不是使用persist来持久化新实体(插入行) – Artem

回答

0

我相信你指的是公司不被从A更新公司表中所示,当一直存在被用户调用的实体。

您是否尝试过级联属性?这意味着对于需要保存/更新映射实体(子)的情况,当父实体保存/更新时(当inverse = true时反之亦然)。

我也注意到了userId上的(updatable = false),但在updateUserCompany方法中调用了setParameter()。我认为这已经被照顾了。