java - JPQL - 在没有不必要的选择的情况下更新外键 ID

标签 java hibernate jpa jpql

我有以下数据库架构:

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;
    ...
}

现在我有了 countryIdcityId。我需要更新表格城市并更改它的国家/地区。我会在 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/

相关文章:

java - 无法通过 Java 代码连接到服务器。获取 javax.net.ssl.SSLHandshakeException : Received fatal alert: handshake_failure

java - 编写 Hadoop 减少输出到 Elasticsearch

java - 在 Spring Boot 中创建数据库表后运行自定义脚本

java - org.h2.jdbc.JdbcSQLException : Schema "SYS" not found; SQL statement: select name from sys. 序列 [90079-192]

java - Hibernate 更改 @Formula 中的别名

java - 如何在 Spring boot 中使用 JPA 中的 Criteria?

java - 查找图像中迷宫走廊的大小

jpa - QueryDSL 连接表错误

jpa - 是否可以通过并测试 JPA 中的空列表?

java - 实现 AbstractMultiTenantConnectionProvider