Search code examples
javahibernatejpajpql

JPQL - update foreign key id without unnecessary selects


I have the following database schema:

create table country (
  id integer primary key
);

create table city (
  id integer primary key, 
  country_id integer references country
);

and mappings:

@Entity
class Country {
    @Id private Integer id;
    ...
}

@Entity
class City {
    @Id private Integer id;
    @ManyToOne private Country country;
    ...
}

Now I have countryId and cityId. I need to update table city and change it's country. I would do in SQL something like that: update city set country_id = :countryId where id = :cityId.

I can update simple properties with JPQL with similar syntax. But how can I update foreign key reference in the example above?

Of course I can get corresponding entities by id and update java entities, something like

City city = em.find(cityId, City.class);
Country country = em.find(countryId, Country.class);
city.setCountry(country);

but this code will issue 2 unnecessary selects. I would like to avoid that.


Solution

  • I believe the EntityManager.getReference() method exists just for this purpose. See javadoc