JPA - 更新孩子对父母的尊敬

时间:2016-12-15 17:19:44

标签: java hibernate jpa jax-rs named-query

如果我有这样的家长

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();

但用户未在DB中更新?如何在DB中更新它?

由于

1 个答案:

答案 0 :(得分:0)

我相信你指的是公司表中没有从A更新到B的公司,当在用户实体上调用persist时。

您是否尝试过级联属性?它适用于需要保存/更新映射实体(子)的场景,保存/更新父实体时(当inverse = true时反向为真)。

我还注意到userId上的(updatable = false),但是在updateUserCompany方法中调用了setParameter()。我认为这已经得到了解决。