Hibernate Search + Elastic Search + concurrency error log

Hi ,
Using Hibernate Search


and fallback to this some time not very frequent

2021-01-27 11:17:09,513 ERROR org.hibernate.AssertionFailure [https-jsse-nio-8455-exec-2] HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: force initialize loading collection
org.hibernate.AssertionFailure: force initialize loading collection
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:775)
at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:973)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:359)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:324)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2406)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:64)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:144)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2384)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:744)
at org.hibernate.type.EntityType.resolve(EntityType.java:467)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:226)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:160)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.performTwoPhaseLoad(AbstractRowReader.java:255)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:215)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:105)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:197)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4350)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:569)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:537)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:208)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:332)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:108)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:74)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118)
at org.hibernate.internal.SessionImpl.fireLoadNoChecks(SessionImpl.java:1168)
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1033)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:687)
at org.hibernate.type.EntityType.resolve(EntityType.java:464)
at org.hibernate.type.ManyToOneType.resolve(ManyToOneType.java:240)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:226)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:160)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1179)
at org.hibernate.loader.Loader.processResultSet(Loader.java:1028)
at org.hibernate.loader.Loader.doQuery(Loader.java:964)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
at org.hibernate.loader.Loader.doList(Loader.java:2797)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
at org.hibernate.loader.Loader.list(Loader.java:2624)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:396)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1396)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1558)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1526)
at org.hibernate.query.Query.getResultList(Query.java:165)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:76)
at org.hibernate.search.mapper.orm.search.loading.impl.HibernateOrmEntityIdEntityLoader.doLoadEntities(HibernateOrmEntityIdEntityLoader.java:140)
at org.hibernate.search.mapper.orm.search.loading.impl.HibernateOrmEntityIdEntityLoader.loadBlocking(HibernateOrmEntityIdEntityLoader.java:70)
at org.hibernate.search.engine.search.loading.spi.DefaultProjectionHitMapper.loadBlocking(DefaultProjectionHitMapper.java:42)
at org.hibernate.search.backend.elasticsearch.search.query.impl.ElasticsearchLoadableSearchResult.loadBlocking(ElasticsearchLoadableSearchResult.java:69)
at org.hibernate.search.backend.elasticsearch.search.query.impl.ElasticsearchSearchQueryImpl.fetch(ElasticsearchSearchQueryImpl.java:130)
at org.hibernate.search.backend.elasticsearch.search.query.impl.ElasticsearchSearchQueryImpl.fetch(ElasticsearchSearchQueryImpl.java:48)
at org.hibernate.search.engine.search.query.spi.AbstractSearchQuery.fetch(AbstractSearchQuery.java:40)
at be.belgiantrain.sale.service.SaleSearchServiceImpl.search(SaleSearchServiceImpl.java:129)
at sun.reflect.GeneratedMethodAccessor406.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at be.belgiantrain.sale.service.$Proxy189.search(Unknown Source)
at be.belgiantrain.sale.service.SaleSearchWebService.search(SaleSearchWebService.java:72)
at be.belgiantrain.sale.service.SaleSearchWebService$$FastClassBySpringCGLIB$$46de3fd.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at be.belgiantrain.sale.service.SaleSearchWebService$$EnhancerBySpringCGLIB$$d35cb05.search()
at sun.reflect.GeneratedMethodAccessor404.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at be.belgiantrain.security.config.JwtAuthorizationFilter.doFilterInternal(JwtAuthorizationFilter.java:60)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:154)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:122)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:107)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
2021-01-27 11:17:09,517 ERROR org.apache.juli.logging.DirectJDKLog [https-jsse-nio-8455-exec-2] Servlet.service() for servlet [dispatcherServlet] in context with path [/api] threw exception [Request processing failed; nested exception is org.hibernate.AssertionFailure: force initialize loading collection] with root cause
org.hibernate.AssertionFailure: force initialize loading collection
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:775)
at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:973)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:359)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:324)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2406)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:64)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:144)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2384)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:744)
at org.hibernate.type.EntityType.resolve(EntityType.java:467)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:226)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:160)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.performTwoPhaseLoad(AbstractRowReader.java:255)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:215)

Hi.

This was a Beta version of Hibernate Search. Although I’ve never seen this problem, it’s very possible that it no longer occurs in recent version. Please upgrade to 6.0.0.Final and tell us if this still occurs?

it seems like multithread environment has this issue.
this product is in early prod release and cant be change soon.
but we never have this issue in any of test environments
concurrency is about 200.

Exception in multi-thread application · Issue #167 · dkpro/dkpro-uby · GitHub

Exception in multi-thread application · Issue #167 · dkpro/dkpro-uby

Hello, I am using your library with the Hibernate support and it works great. At the moment I have started to use an improved implementation of my algorithm that uses multiple threads. When the num…

Indeed, you should not use the same Session in multiple threads.

here is the configurations

and in hibernate search
image

image

image

and rest other crud operations are done using spring data jpa

Well you’re using spring, so you shouldn’t create the entity manager yourself. Let Spring create it, and inject it into your methods. Try something like this:

@Bean
@Autowired
public SearchSession searchSession(EntityManager entityManager) {
    return Search.session(entityManager);
}

@Bean
@Autowired
public SearchMapping searchMapping(EntityManagerFactory entityManagerFactory) {
    SearchMapping mapping = Search.mapping(entityManagerFactory);
    if (reindex) {
        mapping.scope(Object.class)
                .massIndexer().dropAndCreateSchemaOnStart(true)
                .threadsToLoadObjects(6).startAndWait();
    }
    return mapping;
}

And above all, UPGRADE TO 6.0.0.Final.

@yrodiere Appreciated your quick response as always.
I am currently trying to replicate issue in non prod environment .
once done Ill make changes and let u know the result.

in spring boot we have to create EntityManager from EntityManagerFactory; that way it wont work

I tried this configuration as well
@PersistenceContext
private EntityManager entityManager;

@Bean
@Transactional

// @Autowired
public SearchSession searchSession(/final EntityManager entityManager/) throws InterruptedException {
// EntityManager entityManager = entityManagerFactory.createEntityManager();
/SearchSession searchSession = Search.session(entityManager);
if (reindex) {
searchSession.schemaManager().dropAndCreate();
searchSession.massIndexer().threadsToLoadObjects(6).startAndWait();
}
/
return Search.session(entityManager);
}

but I landed to this error
org.hibernate.search.util.common.SearchException: HSEARCH800016: Unable to access Hibernate ORM session: Session/EntityManager is closed

@yrodiere Same error, even after

2021-01-29 07:26:35,057 INFO be.belgiantrain.sale.service.SaleSearchServiceImpl [https-jsse-nio-8455-exec-6] Search(clazz=be.belgiantrain.sale.model.SaleSaga, arguments={salesOrder.creationDate=[date, 2020-01-26T01:00:00Z, 2021-01-29T00:59:00Z]}, tickets=null, passes=null, payments=null, saleSagas=null, salesOrders=null, items=null)
2021-01-29 07:26:35,057 INFO be.belgiantrain.sale.service.SaleSearchServiceImpl [https-jsse-nio-8455-exec-6] Range of values : 2020-01-26T01:00:00Z => 2021-01-29T00:59:00Z
2021-01-29 07:26:35,063 ERROR org.hibernate.AssertionFailure [https-jsse-nio-8455-exec-9] HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: possible non-threadsafe access to the session
org.hibernate.AssertionFailure: possible non-threadsafe access to the session

2021-01-29 07:26:35,286 WARN org.hibernate.engine.loading.internal.LoadContexts [https-jsse-nio-8455-exec-7] HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@445dfe5brs=oracle.jdbc.driver.OracleResultSetImpl@21092fbb
2021-01-29 07:26:35,287 WARN org.hibernate.engine.loading.internal.CollectionLoadContext [https-jsse-nio-8455-exec-7] HHH000160: On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [2] entries
2021-01-29 07:26:35,287 INFO be.belgiantrain.sale.service.SaleSearchServiceImpl [https-jsse-nio-8455-exec-7] Search(clazz=be.belgiantrain.sale.model.SaleSaga, arguments={salesOrder.creationDate=[date, 2020-01-26T01:00:00Z, 2021-01-29T00:59:00Z]}, tickets=null, passes=null, payments=null, saleSagas=null, salesOrders=null, items=null)
2021-01-29 07:26:35,287 INFO be.belgiantrain.sale.service.SaleSearchServiceImpl [https-jsse-nio-8455-exec-7] Range of values : 2020-01-26T01:00:00Z => 2021-01-29T00:59:00Z
2021-01-29 07:26:35,295 ERROR org.hibernate.AssertionFailure [https-jsse-nio-8455-exec-1] HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: possible non-threadsafe access to the session
org.hibernate.AssertionFailure: possible non-threadsafe access to the session
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:158)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.performTwoPhaseLoad(AbstractRowReader.java:255)

this only happen we have data in result-set and with multiple threads

Am I incorrect or are you creating a global SearchSession bean that you reuse across threads?

If so, you cannot do that, sessions are not threadsafe.

1 Like

@gsmet You’re correct ! let me check if it work like u asked to do so

if not the case then how subjected entity which is not being persistent and still in transient state got to know about the change .
i.e. if entity a of session1 has some changes which is not persistent yet and same time a search request came in session2 know about this change ?

Actually you can, but only if the underlying entity manager is a proxy created by Spring 5.3+.

@Swarnkar The StackOverflow question you used to justify your creating of the entity manager manually is only valid with Spring 5.2 and below.

Last time I checked, when you use Hibernate Search 6.0.0.Final and Spring 5.3+, you can just use the code I gave you.

In any case, the workaround you gave as a solution to that stackoverflow question is incorrect, since it will result in creating one global entity manager, and that just cannot work.

Whatever you do, revert your workaround and let Spring create the entity manager. What you did here leads you to re-use the entity manager in multiple threads, and this will always cause the errors you’re seeing, referring to “unsafe use of the session”.

To retrieve the SearchSession with Spring 5.3+, just use the code I gave above:

@Bean
@Autowired
public SearchSession searchSession(EntityManager entityManager) {
    return Search.session(entityManager);
}

@Bean
@Autowired
public SearchMapping searchMapping(EntityManagerFactory entityManagerFactory) {
    SearchMapping mapping = Search.mapping(entityManagerFactory);
    if (reindex) {
        mapping.scope(Object.class)
                .massIndexer().dropAndCreateSchemaOnStart(true)
                .threadsToLoadObjects(6).startAndWait();
    }
    return mapping;
}

To retrieve the SearchSession with Spring 5.2 and below, I think you should give up on making the SearchSession a bean. It’s possible, but requires advanced usage of Spring, way beyond the scope of the Hibernate forums.

Instead, just inject the EntityManager in your SaleSearchServiceImpl, and retrieve the searchSession at the very last moment, when you actually need it. Never, ever store it in a class member. I.e. do this:

public class SaleSearchServiceImpl implement SaleSearchService {

    private final EntityManager entityManager;

    @Autowired.
    public SaleSearchServiceImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    @Transactional // You need a transaction to use the Spring-provided entityManager
    public List<Sale> search(String terms) {
        // This SearchSession is only valid during the transaction, don't store it anywhere.
        SearchSession searchSession = Search.session(entityManager);
        return searchSessio.search(Sale.class)
                .where(f -> f.simpleQueryString().field("myField").matching(terms))
                .fetchHits(20);
    }

}

I haven tried to move to latest version of spring but the other way it is working. Will plan if in future we have urgent fix in prod for this problem and so cant do it right now.
@yrodiere and @gsmet thanks for your quick response to move a stable build in prod in our system