在线程 运行 方法内自动装配 sessionfactory 不起作用

Autowiring sessionfactory inside thread run method not working

我正在尝试将休眠会话工厂自动连接到线程的 运行 方法中。但是显示如下错误

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

我的class如下

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());

}


}

我该如何解决这个问题?

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

确保你的 class 被注释为 @Component 用于 spring 依赖注入。

Refer this doc for Configuring Session Factory Bean

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