【问题标题】:JPQL - update foreign key id without unnecessary selectsJPQL - 更新外键 id 没有不必要的选择
【发布时间】: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;
    ...
}

现在我有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 个不必要的选择。我想避免这种情况。

【问题讨论】:

标签: java hibernate jpa jpql


【解决方案1】:

我相信 EntityManager.getReference() 方法的存在就是为了这个目的。 见javadoc

【讨论】:

  • 例如,如果您使用@Query 注解,则没有意义。
【解决方案2】:

我找到了解决方案。这似乎很简单。只需创建新的实体对象,初始化其 id 并将其作为参数传递给 JPQL 更新查询:

Country country = new Country();
country.setId(countryId);
Query query = em.createQuery("update City set country = :country where id = :cityId");
query.setParameter("country", country);
query.setParameter("cityId", cityId);
query.executeUpdate();

显然 JPA 并不关心 country 对象是从数据库中检索还是手动创建的,只需设置 id 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多