Min Naing Oo
Min Naing Oo

Reputation: 1095

Inserting/Updating an entity with another referenced entities in Hibernate

When inserting/updating an entity in hibernate and want to update changes only to the updating entity, is it ok to just set the ID of the foreign key holding reference entity? eg.

UserRole userRole = new UserRole();
userRole.setId(1);
User user = new User();
user.setUserRole(userRole);

userDao.update(user);
-OR-
userDao.insert(user);

Or do I need to get full referenced entity from database everytime? eg.

UserRole userRole = userRoleDao.getById(1);
User user = new User();
user.setUserRole(userRole);

userDao.update(user);
-OR-
userDao.insert(user);

Both seems to work fine for me. But I'm afraid there'll be performance impact on second approach and the first one looks like bad code.

Upvotes: 3

Views: 545

Answers (2)

Grigory Kislin
Grigory Kislin

Reputation: 17980

The best practice is using EntityManage.getReference() / JpaRepository.getReferenceById().
They involve real apply to DB according persistent provider implementation (for Hibernate could be managed by AvailableSettings.JPA_PROXY_COMPLIANCE, by default false - no apply)

See also JPA setting referenced property without retrieving it. Best practices - with cascade first apploach doesn't work.

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26961

Both are correct if id is the primary key of the UserRole.

  • I prefer first approach.

When an entity has been previously persisted you only need the primary key to reference already created entities. This happens also in the database, if you take a look at User table, you won't find a complete UserRole, you will just find the primary key.


But I'm afraid there'll be performance impact on second approach

All depends where the database is, impact in performance will be negligible if you don't make this operation million of times, but time can be increased if remote database AND bad connection.

Upvotes: 4

Related Questions