cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Session from manually created Spring TX

chris3
Graph Buddy

Hello Neo4j and Spring Gurus!

I mainly use OGM and @Autwired Sessions and Neo4jRepositories but for certain cronjob-like batch operations I frequently need to handle my own transactions (e.g. begin and commit inside a loop)

Currently I use an @Autowired SessionFactory then tx=session.beginTransaction() and tx.commit()
BUT
isn't there a way to manually get a "real" Spring TX from the PlatformTransactionManager and then get the OGM Session from that?
... so that I could even do a TransactionSynchronizationManager.registerSynchronization for calling code after the TX has been committed?

@Autowired private PlatformTransactionManager txManager;
...
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
for (...) {
  TransactionStatus txStatus = txManager.getTransaction(def);
  * HOW TO GET CURRENT SESSION FROM TX HERE ??? *
  session.query(....)
  TransactionSynchronizationManager.registerSynchronization(
    new TransactionSynchronizationAdapter() {
      public void afterCommit() {...}
    });
  ..
  if (ok) txManager.commit(txStatus);
}

Cheers,
Chris

2 REPLIES 2

Hi,

The key point here is: Both our Session and the underlying SessionFactory are aware of the ongoing Spring TX. Just let the session autowire into your thing and it will be aware of an ongoing implicit (@Transactional) or explicit transaction. The easiest thing to accomplish the later is using a transaction template:

import org.springframework.transaction.support.TransactionTemplate;

@Bean
TransactionTemplate transactionTemplate(PlatformTransaction manager) {
    return new TransactionTemplate(manager); 
}

And autowire that:

public class YourService {
    private final TransactionTemplate transactionTemplate;

    private final Session session;

    public YourService(TransactionTemplate transactionTemplate, Session session) {
       this.transactionTemplate = transactionTemplate;
       this.session = session;
    }

    public Object whatEver() {
        return this.transactionTemplate.execute(t -> {
            // do your thing with session. The session is a proxy, that is 
            // aware of the ongoing Spring TX
        });
    }
}

chris3
Graph Buddy

Oh cool - I had no idea that a single @Autowired Session would work like that
Thank you so much for your help!