'Hibernate does another select before save
I have the following sample code:
@Transactional
public void someMethod() {
MyEntity myEntity = myRepo.findById(1).orElse(null);
if (myEntity != null) {
myEntity.setValue("something");
myRepo.save(myEntity);
}
}
And myRepo is an instance of:
public interface MyRepo extends CrudRepository<MyEntity, Integer> {}
So I can see the first SELECT is coming from myRepo.findById(1), which makes sense. But when the code runs to myRepo.save(myEntity), Hibernate somehow thinks the myEntity returned from findById() is not managed and so it does another SELECT again to create a managed entity, then replace its value using myEntity, then does the UPDATE.
Could you please explain why another SELECT is required and how can you avoid it? Also, the @Transactional annotation above the method does not change this behaviour with or without it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
