Posts 关于 spring&hibernate session 连接问题
Post
Cancel

关于 spring&hibernate session 连接问题

下面的此类错误产生是因为在不同的线程中使用了 HibernategetCurrentSession,由于使用了不同的线程池处理方案,那么子线程无法继承父线程中的 变量(ThreadLocal) ,在 Spring 的整合中,如:SimpleAsyncTaskExecutorThreadPoolTaskExecutor 线程池,前者不会携带父线程中的变量,而后者会携带;当然你也可以选择重新利用 HibernatesessionFactory 进行 openSession 的操作,这样也能够解决此类问题。

1
spring boot org.hibernate.LazyInitializationException: could not initialize proxy - no Session

如果 @Async 异步问题

Annotation

1
2
3
4
@Bean(initMethod = "initialize")
public TaskExecutor taskExecutor() {
    return new ThreadPoolTaskExecutor();
}

XML

1
2
<task:executor id="threadPoolTaskExecutor" keep-alive="3000" pool-size="1000" queue-capacity="200"/>
<task:annotation-driven executor="threadPoolTaskExecutor"/>

如果 ApplicationEventPublisher 异步问题

Annotation

1
2
3
4
5
6
7
8
9
10
11
12
@Bean
public ApplicationEventMulticaster applicationEventMulticaster() {
    SimpleApplicationEventMulticaster eventMulticaster
            = new SimpleApplicationEventMulticaster();
    eventMulticaster.setTaskExecutor(taskExecutor());
    return eventMulticaster;
}

@Bean(initMethod = "initialize")
public TaskExecutor taskExecutor() {
    return new ThreadPoolTaskExecutor();
}

参考资料

https://stackoverflow.com/questions/46050522/spring-boot-closes-hibernate-session-on-shutdown-before-async-methods-are-fin

https://stackoverflow.com/questions/25083295/spring-async-null-hibernate-session-on-lazy-collection

This post is licensed under CC BY 4.0

InfluxDB 数据备份与恢复方式进行迁移

三十分钟完成 Jira 安装与破解

Comments powered by Disqus.