Create a Neo4J DAO using Spring Data Neo4j

https://www.baeldung.com/spring-data-neo4j-intro explains how to configure Spring with Neo4J and use repositories to get data.

https://neo4j.com/docs/ogm-manual/current/tutorial/#tutorial-session shows how to create a CRUD service using the Session object.

As written in the Session Javadoc, Session object is not thread safe.

session-not-thread-safe

 

Most of our DAO objects are singletons used by many threads. So the Session class member should be replaced by a SessionFactory which will create a new Session each time we need it.

first-version

The Service calling the DAO is annotated with @Transactional to have transaction support on all his methods.

service

Running this code causes a org.neo4j.ogm.exception.core.TransactionManagerException: Transaction is not current for this threadtransactionmanagerexception

The code of Neo4jTransactionManager shows that a new Session is opened when starting a transaction.neo4j-dao-begin-transaction

And it is stored in the TransactionSynchronizationManager, a « thread local holder » that is cleared at the end of the transaction.

session-holder

The created Session can easily be retrieved through the TransactionSynchronizationManager.

fina-get-session

The following DAO work fine if we are in a Spring-managed transactional context

neo4j-dao

Laisser un commentaire