2016-09-22 110 views
0

在我的Spring Boot Webapp中,我有一个调度程序类@EnableScheduling 和@EnableAsync,晚上由@Scheduled运行。类是获得与会话:在Spring Boot Scheduler中获取JPA会话

Session session = entityManager.unwrap(Session.class); 

导致此异常:

org.hibernate.SessionException: Session is closed! 

什么是获得预定的任务会话的正确方法?

这里是下面的代码:

 Session session = em.unwrap(Session.class); 
     Query query = session.createQuery("SELECT l FROM Lei l ORDER BY l.id"); 
     query.setFetchSize(Integer.valueOf(1000)); 
     query.setReadOnly(true); 
     query.setLockMode("a", LockMode.NONE); 
     // http://stackoverflow.com/questions/5067619/jpa-what-is-the-proper-pattern-for-iterating-over-large-result-sets 
     ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); 
     while (results.next()) { 
      Lei lei = (Lei) results.get(0); 
      writer.writeLEI(lei); 
     } 
     results.close(); 
     session.close(); 
+0

你可以发布一些更多的代码? – jahra

+0

为什么你需要'Session' ......我使用普通的'EntityManager'有什么问题? –

回答

0

这是我刚刚创建(我使用的是春天开机1.4所有的默认配置)的测试服务:

@Service 
public class ScheduledService { 
    @Autowired 
    private EntityManager entityManager; 

    @Async 
    @Scheduled(fixedRate = 500L) 
    @Transactional 
    private void reportCurrentTime() { 
     entityManager = entityManager.getEntityManagerFactory().createEntityManager(); 
     Session session = entityManager.unwrap(Session.class); 

     System.out.println(session.hashCode()); 
    } 
} 

然后我就可以看到控制台中的会话哈希码

1410300721 
966623925 
181180995 
1606490891 
1882727729 
635804073 
1259672020 
484131582 
+0

我也可以显示hashCode,但后来我执行一个查询,我得到上述异常 – ropo

+0

在你的例子中执行查询为我工作。现在我需要弄清楚为什么它在我的项目中不起作用 – ropo

0

发现问题。愚蠢的我!我关闭了会话

session.close();