【发布时间】:2015-02-19 04:03:08
【问题描述】:
我有以下数据库架构:
create table country (
id integer primary key
);
create table city (
id integer primary key,
country_id integer references country
);
和映射:
@Entity
class Country {
@Id private Integer id;
...
}
@Entity
class City {
@Id private Integer id;
@ManyToOne private Country country;
...
}
现在我有countryId 和cityId。我需要更新表格城市并更改它的国家。我会在 SQL 中做类似的事情:update city set country_id = :countryId where id = :cityId。
我可以使用类似语法的 JPQL 更新简单属性。但是如何更新上例中的外键引用呢?
当然可以通过id获取对应的实体,更新java实体,类似
City city = em.find(cityId, City.class);
Country country = em.find(countryId, Country.class);
city.setCountry(country);
但此代码将发出 2 个不必要的选择。我想避免这种情况。
【问题讨论】:
-
对于 JPA 和 Hibernate,请检查 Vlad Mihalcea:vladmihalcea.com/entitymanager-find-getreference-jpa