0

I was asked in an interview to tell all the queries that are executed when the method below is called:

public class UserService {

@PersistanceContext
private EntityManager entityManager;

@Transactional
public void updateUser(long userId, UserDTO userDTO) {
    User user = entityManager.find(userId);
    if (user != null) {
         user.setName(userDTO.getName());
    }
}

}

Because I only see a call to entityManager.find my answer was 1. The feedback was wrong. Is it true that the find method would hit the database more than once? I assume user.setName does not hit the database because there's no explicit call to merge/persist.

Carlos Gonzalez
  • 607
  • 1
  • 5
  • 13
  • 1
    depends on the database model, mapping and retrieval settings. a single user can be spread over more than one table, with eager loading you have one query per table, perhaps. – Curiosa Globunznik Sep 19 '20 at 17:31
  • @curiosa So there would be two queries executed, right? One for fetching and one for updating (Assuming user is stored in single table) – Raj Sep 20 '20 at 13:16
  • 1
    @Raj hibernate does a lot of weird stuff in the background, but if we focus just on this one table ... maybe, at the moment nothing comes to my mind that contradicts your statement. If you consider the wider context... what if the statement fails for some constraint reasons, what will the error handling do, are there some hibernate hooks that do some underlying furhter processing? many things could come in the way. But if you have a plain pojo, mapped straight forward, no errors, no extras, no strange caching, no dependent objects loaded eagerly, yes, then I'd say it's those 2 qeries. – Curiosa Globunznik Sep 20 '20 at 15:30

0 Answers0