【问题标题】:Autowiring sessionfactory inside thread run method not working在线程运行方法中自动装配 sessionfactory 不起作用
【发布时间】:2016-11-18 04:21:47
【问题描述】:

我正在尝试将休眠会话工厂自动装配到线程的运行方法中。但它显示以下错误

Exception in thread "Timer-6" org.hibernate.HibernateException: No Session found for current thread

我的班级如下

public class CroneJobNew extends TimerTask {
@autowired
private SessionFactory sessionFactory ; 


@Override
public void run() {
List<Shop>  shops = sessionFactory.getCurrentSession().createCriteria(Shop.class).list();
System.out.println("shops size"  + shops.size());

}


}

我该如何解决这个问题?

【问题讨论】:

  • 是否有任何具体原因为什么您不使用@EnableAsync@Async 注释来处理线程?使用这些注释进行自动装配就像一个魅力..
  • 我正在使用这个线程来创建一个计时器。我的类CroneJobNew默认实现了这个线程类。
  • 看看这个答案,Spring and hibernate: No Session found for current thread,我认为这会有所帮助。

标签: spring multithreading hibernate autowired


【解决方案1】:

您可以将方法 getCurrentSession() 替换为 openSession() 并且您需要添加 session.beginTransaction() (最后关闭它),因为您在没有@Transactional 范围的情况下工作

【讨论】:

  • 我在运行方法中使用了多个 sessionFactory.openSession()。所以当我使用 sessionFactory.close(); 关闭会话工厂时;它在线程“Timer-0”org.hibernate.service.UnknownServiceException 中显示以下错误异常:请求未知服务
【解决方案2】:

确保您的类使用 @Component 进行注释以进行 spring 依赖注入。

Refer this doc for Configuring Session Factory Bean

如果您使用的是 spring-boot,则必须手动配置 SessionFactory Bean 才能使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多