How to use StatelessSession with Spring JPA and Hibernate data?

I am using Spring + Spring Data JPA with Hibernate, and I need to perform some big and expensive database operations.

How can I use StatelessSession to perform these operations?

+7
source share
3 answers

The solution is to implement the Spring factory bean to create this StatelessSession and implement it in the implementation of custom repositories:

 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 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 the StatelessSessionFactoryBean code. Hope this helps someone, it worked like a charm for me.

+11
source

To get even better performance results, you can enable jdbc batch instructions in SessionFactory / EntityManager by setting the hibernate.jdbc.batch_size property in the SessionFactory configuration (i.e. LocalEntityManagerFactoryBean ).

To have the best advantage for inserting / updating a jdbc batch, write as many objects of the same type as possible. Hibernate will detect when you write another type of entity, and will automatically clear the package, even if it has not reached a certain lot size.

Using StatelessSession behaves basically the same as using Spring JdbcTemplate . The advantage of using StatelessSession is that SQL matching and translation is handled by Hibernate. When you use my StatelessSessionFactoryBean , you can only mix Session and StatelessSession in one transaction. But be careful with modifying the Entity loaded by Session and storing it with StatelessSession , because this will lead to locking issues.

+2
source

No need to do this with this:

 public void bulkInsert(Collection<YourClass> yourObjects) { if (yourObjects == null || yourObjects.isEmpty()) { return; } yourRepository.save(yourObjects); } 
-3
source

All Articles