Spring Transaction Manager Usage

Spring Transaction Manager Usage

Dependencies

Include this dependency in your project:

<dependency> <groupId>org.ops4j.orient</groupId> <artifactId>orient-spring-tx</artifactId> <version>${ops4j.orient.version}</version> </dependency>

Spring Beans

To work with the OPS4J Orient Spring Transaction Manager, include a transaction manager bean and a suitable database factory bean in your Spring application context. The required bean classes are:

  • org.ops4j.orient.spring.tx.OrientTransactionManager

  • org.ops4j.orient.spring.tx.OrientDocumentDatabaseFactory

  • org.ops4j.orient.spring.tx.OrientGraphDatabaseFactory

  • org.ops4j.orient.spring.tx.OrientObjectDatabaseFactory

A database factory wraps an Orient database pool and is configured with database URL, username and password and minimum and maximum pool size.

Example

@Configuration @EnableTransactionManagement public class ObjectSpringTestConfig { @Bean public OrientTransactionManager transactionManager() { OrientTransactionManager bean = new OrientTransactionManager(); bean.setDatabaseManager(databaseFactory()); return bean; } @Bean public OrientObjectDatabaseFactory databaseFactory() { OrientObjectDatabaseFactory manager = new OrientObjectDatabaseFactory(); manager.setUrl("local:target/test"); manager.setUsername("admin"); manager.setPassword("admin"); return manager; } }

Working with declarative transactions

To work with the Spring transaction manager and declarative transactions, inject a concrete database factory bean into your classes and annotate your transactional methods with @Transactional. The transaction manager will automatically intercept these methods, acquire a database handle from the pool, begin, commit or rollback a transaction as required, and close the database handle.

A database object can be obtained by invoking the db() method of the database factory bean. This object is only valid within a @Transcational method. For actions that do not support transactions, e.g. for registering an entity class, a @Transactional method is still required to let the interceptor open and close the database, but using Propagation.NEVER to avoid opening a transaction.

It is not currently possible to directly inject a database object, since OrientDB database classes are not proxyable. This is the rationale for using the db() method.

Example

public class TransactionalObjectService { @Autowired private OrientObjectDatabaseFactory dbf; @Transactional(propagation = Propagation.NEVER) public void registerEntityClasses() { dbf.db().getEntityManager().registerEntityClass(Person.class); } @Transactional public void commitAutomatically() { Person person = dbf.db().newInstance(Person.class); person.setFirstName("Donald"); person.setLastName("Duck"); dbf.db().save(person); } }