mardi 28 juin 2016

Automatically reusing existing entity in ManyToMany/ManyToOne relationship (JPA)


JPA and Hibernate are used to retrieve and persist entities. There is a User table and it contains a Country, which is represented in another table.

I would like to insert a new user into User table. This new user is from country that is already inserted in the Country table. To assign the new user the existing country I could retrieve the country object from the database and set it to the User object - it works as expected, a relationship is created between user and the existing country, no new rows are inserted to Country table.

Is it possible to get the same behavior without retrieving Country objects from database, based just on the value that I set to the Country object in the JPA entity in Java?

For example:

User user = new User("test user");
user.setCountry(new Country("USA"));
entityManager.persist(user);

I would like JPA/Hibernate to automatically check if the country, which code is USA (code is saved in a column in Country table and it is unique), already exists in the database. If it does - use the existing Country object so that a new entry in the database would not be created, if it does not exist - insert a new country in the Country table.

Thank you!


Aucun commentaire:

Enregistrer un commentaire