Is there a way to simply obtain detached entities in a Springboot application?
In order to illustrate (I leave the strict minimum) :
Here a repository of entity A:
public interface ARepository extends JpaRepository<A, Long> { (...) }
Here a manager of object from A class (does some atomicals operations):
public class AManager {
private ARepository aRepository;
@Transactional(readOnly = true)
public A getA(long id) {
return aRepository.findOne(id);
}
}
Here a service of object from A class (does more complexes operations):
public class AService {
private AManager aManager;
@Transactional(readOnly = true)
public A getA(long id) {
return aManager.getA(id);
}
}
And here a jsp which calls my service:
(...)
A a = aService.getA(1);
a.someproperty = value; // Do not automatically commit this modification!!!!
(...)
For safety, I prefer that the entities I get out of the service are detached (in fact not more managed). But I have lots of entities and often collections of them.
The only solution I found for the moment is:
public A getA(long id) {
A a= aRepository.findOne(id);
Hibernate.initialize(a.collectionProperty);
entityManager.detach(a);
return a;
}
Did I have this only solution? What to do when I have a Collection of entities? Is there any configuration to manage that in Springboot? in Hibernate?
Since it is a spring boot application, Spring Boot by default registers OpenEntityManagerInViewInterceptor. This will open the session
(or entityManager), binds it to the transaction
when request starts and and closes it after the request processing is done.
So any changes you are make till the request is not completed are getting tracked, thus are the JSP modifications to the entities, and committed to the DB.
So I think if you set spring.jpa.open-in-view=false
in spring boot conf file application.properties
or yaml file, that should help.