I'm using Spring + Spring Data JPA with Hibernate and I need to perform some large and expensive database operations.
How I can use a StatelessSession
to perform these kind of operations?
A solution is to implement a Spring factory bean to create this StatelessSession
and inject it in your custom repositories implementation:
public class MyRepositoryImpl implements MyRepositoryCustom {
@Autowired
private StatelessSession statelessSession;
@Override
@Transactional
public void myBatchStatements() {
Criteria c = statelessSession.createCriteria(User.class);
ScrollableResults itemCursor = c.scroll();
while (itemCursor.next()) {
myUpdate((User) itemCursor.get(0));
}
itemCursor.close();
return true;
}
}
Check out the StatelessSessionFactoryBean
and the full Gist here. Using Spring 3.2.2, Spring Data JPA 1.2.0 and Hibernate 4.1.9.
Thanks to this JIRA and the guy who attached StatelessSessionFactoryBean
code. Hope this helps somebody, it worked like a charm for me.