vbe*_*nar 5 java hibernate jpa jpql
我有以下数据库架构:
create table country (
id integer primary key
);
create table city (
id integer primary key,
country_id integer references country
);
Run Code Online (Sandbox Code Playgroud)
和映射:
@Entity
class Country {
@Id private Integer id;
...
}
@Entity
class City {
@Id private Integer id;
@ManyToOne private Country country;
...
}
Run Code Online (Sandbox Code Playgroud)
现在我有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);
Run Code Online (Sandbox Code Playgroud)
但这段代码会发出 2 个不必要的选择。我想避免这种情况。
| 归档时间: |
|
| 查看次数: |
2626 次 |
| 最近记录: |