I need to get either an existing Session or SessionFactory or EntityManagerFactory, which were created via Spring Boot 3 and Hibernate 6.
But while all solutions I found return valid instances of those classes, they don't work. In the end they crash with something like:
java.lang.IllegalArgumentException: Unable to locate persister:
org.hibernate.collection.spi.PersistentBag
Code:
// Using either @PersistenceContext or @Autowired doesn't make a difference.
@PersistenceContext
private EntityManager entityManager;
@Transactional
public <T> T merge(T object) {
Session session = entityManager.unwrap(Session.class);
// Crash
session.merge(object);
The solutions for this exception are to fix the entity scanning. But the entity scan works perfectly, Spring saves, finds and loads wonderful everywhere. It seems that this directly instantiated Session / SessionFactory / EntityManagerFactory creates and scans everything on its own, ignores everything Spring already did, and then complains that nothing can be found / isn't configured / whatever.
Obviously I don't want the application to stop and rebuild everything, just reuse the already existing Spring objects.
How do I do that?
The answers which told to fix the entity scanning in such a case were wrong. The problem is that the exception happens when trying to unproxy a list. But Hibernate doesn't know how to unproxy a list, it does seem to have lost its origin data, so the only solution I found was, but only for lists, to reload the container and initialize the list in that transactions session.
Also session.merge(object)
doesn't reattach the object to the session, so it can't be unproxied after a merge
. Instead session.update(object)
works, although it's marked deprecated.