How do I get a StatelessSession when using Hibernate

1.7k Views Asked by At

I am trying to get a StatelessSession using SessionFactory with the following code:

final Session session = entityManager.unwrap(Session.class);
final SessionFactory sessionFactory = session.getSessionFactory();
final StatelessSession statelessSession = sessionFactory.openStatelessSession();

but when I test the code it fails with the following exception:

java.util.concurrent.ExecutionException: com.lightbend.lagom.javadsl.api.transport.TransportException: java.lang.ClassCastException: org.hibernate.internal.StatelessSessionImpl cannot be cast to org.hibernate.Session
at org.hibernate.persister.entity.AbstractEntityPersister.preInsertInMemoryValueGeneration(AbstractEntityPersister.java:3696)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3673)
at org.hibernate.internal.StatelessSessionImpl.insert(StatelessSessionImpl.java:111)
at org.hibernate.internal.StatelessSessionImpl.insert(StatelessSessionImpl.java:87)
at z.c.e.z.b.r.JPABatchRepository.lambda$null$0(JPABatchRepository.java:49)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:142)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:100)
at z.c.e.z.b.r.JPABatchRepository.wrap(JPABatchRepository.java:42)
at z.c.e.z.b.r.JPABatchRepository.lambda$createBatch$1(JPABatchRepository.java:47)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

I have followed this tutorial Working with stateless session in hibernate and jpa but it doesn't seem to work for me. I am using Lagom Framework and Hibernate 5.3.7.Final. I have also followed the tutorial on Hibernate 5.3.7.Final but to no avail.

Someone mentioned on this StackOverflow question that it was a bug which was supposed to be fixed on 5.2.2, but I am using 5.3.7.Final and still getting the error.

Does anyone know how to get rid of this error? Or a proper way to get an Instance of StatelessSession in Hibernate?

1

There are 1 best solutions below

1
On

According to that error message, the session is already a StatelessSession, so you should be able to unwrap it directly as one:

final StatelessSession session = entityManager.unwrap(StatelessSession.class);