2016-09-22 112 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();