我有以下数据库架构:
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 个不必要的选择。我想避免这种情况。
最佳答案
我相信 EntityManager.getReference() 方法的存在就是为了这个目的。 参见 javadoc
关于java - JPQL - 在没有不必要的选择的情况下更新外键 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27579251/