在Spring Boot Scheduler中获取JPA会话

时间:2016-09-22 07:51:31

标签: spring session spring-boot spring-data-jpa spring-scheduled

在我的Spring Boot Webapp中,我有一个带有@EnableScheduling的调度程序类 和@EnableAsync在晚上由@Scheduled运行。该课程正在通过以下方式获得会议:

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

2 个答案:

答案 0 :(得分:0)

这是我刚刚创建的测试服务(我使用带有所有默认配置的spring boot 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

答案 1 :(得分:0)

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

session.close();