use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.
the class BaseAutoIndexManagerTestClass method executeForIndexes.
void executeForIndexes(Consumer<List<IndexInfo>> consumer) {
Session session = sessionFactory.openSession();
try (Transaction tx = session.beginTransaction()) {
Result indexResult = session.query("CALL db.indexes()", emptyMap());
List<IndexInfo> indexes = new ArrayList<>();
for (Map<String, Object> queryResult : indexResult.queryResults()) {
if (AutoIndex.isNodeOrRelationshipLookup(queryResult)) {
continue;
}
if (isVersionOrGreater("4.0.0")) {
Object[] labelsOrTypes = (Object[]) queryResult.get("labelsOrTypes");
IndexInfo indexInfo = new IndexInfo((String) queryResult.get("uniqueness"), (labelsOrTypes instanceof String[] ? (String[]) labelsOrTypes : new String[0]));
indexes.add(indexInfo);
} else {
String indexType = (String) queryResult.get("type");
String[] labels = queryResult.get("tokenNames") != null ? // 3.5
(String[]) queryResult.get("tokenNames") : // 3.4(-)
new String[] { (String) queryResult.get("label") };
IndexInfo indexInfo = new IndexInfo(indexType, labels);
indexes.add(indexInfo);
}
}
List<IndexInfo> pureIndexes = indexes.stream().filter(indexInfo -> !indexInfo.isConstraintIndex()).collect(toList());
consumer.accept(pureIndexes);
tx.commit();
}
}
use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.
the class BaseAutoIndexManagerTestClass method executeForConstraints.
void executeForConstraints(Consumer<List<ConstraintInfo>> consumer) {
Session session = sessionFactory.openSession();
try (Transaction tx = session.beginTransaction()) {
Result constraintResult = session.query("CALL db.constraints()", emptyMap());
List<ConstraintInfo> constraints = new ArrayList<>();
for (Map<String, Object> stringObjectMap : constraintResult) {
constraints.add(new ConstraintInfo());
}
consumer.accept(constraints);
tx.commit();
}
}
use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.
the class DeleteDelegate method deleteOneOrMoreObjects.
// TODO : this is being done in multiple requests at the moment, one per object. Why not put them in a single request?
private void deleteOneOrMoreObjects(List<?> objects, Set<Object> neighbours) {
Set<Object> notified = new HashSet<>();
if (session.eventsEnabled()) {
for (Object affectedObject : neighbours) {
if (!notified.contains(affectedObject)) {
session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.PRE_SAVE));
notified.add(affectedObject);
}
}
}
for (Object object : objects) {
MetaData metaData = session.metaData();
ClassInfo classInfo = metaData.classInfo(object);
if (classInfo == null) {
session.warn(object.getClass().getName() + " is not an instance of a persistable class");
} else {
MappingContext mappingContext = session.context();
Long id = mappingContext.optionalNativeId(object).filter(possibleId -> possibleId >= 0).orElseGet(() -> {
session.warn(String.format("Instance of class %s has to be reloaded to be deleted. This can happen if the session has " + "been cleared between loading and deleting or using an object from a different transaction.", object.getClass()));
return classInfo.getPrimaryIndexOrIdReader().apply(object).map(primaryIndexOrId -> session.load(object.getClass(), (Serializable) primaryIndexOrId)).flatMap(reloadedObject -> mappingContext.optionalNativeId(reloadedObject)).orElse(-1L);
});
if (id >= 0) {
Statement request = getDeleteStatement(object, id, classInfo);
if (session.eventsEnabled() && !notified.contains(object)) {
session.notifyListeners(new PersistenceEvent(object, Event.TYPE.PRE_DELETE));
notified.add(object);
}
RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
session.doInTransaction(() -> {
try (Response<RowModel> response = session.requestHandler().execute(query)) {
if (request.optimisticLockingConfig().isPresent()) {
List<RowModel> rowModels = response.toList();
session.optimisticLockingChecker().checkResultsCount(rowModels, request);
}
if (metaData.isRelationshipEntity(classInfo.name())) {
session.detachRelationshipEntity(id);
} else {
session.detachNodeEntity(id);
}
// enabled in the first place.
if (notified.contains(object)) {
session.notifyListeners(new PersistenceEvent(object, Event.TYPE.POST_DELETE));
}
}
}, Transaction.Type.READ_WRITE);
}
}
}
if (session.eventsEnabled()) {
for (Object affectedObject : neighbours) {
if (notified.contains(affectedObject)) {
session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.POST_SAVE));
}
}
}
}
use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.
the class Neo4jSession method doInTransaction.
/**
* For internal use only. Opens a new transaction if necessary before running statements
* in case an explicit transaction does not exist. It is designed to be the central point
* for handling exceptions coming from the DB and apply commit / rollback rules.
*
* @param function The callback to execute.
* @param <T> The result type.
* @param txType Transaction type, readonly or not.
* @return The result of the transaction function.
*/
public <T> T doInTransaction(TransactionalUnitOfWork<T> function, boolean forceTx, Transaction.Type txType) {
Transaction transaction = txManager.getCurrentTransaction();
// If we (force) create a new transaction, we are in charge of handling rollback in case of errors
// and cleaning up afterwards.
boolean newTransaction = false;
try {
if (forceTx || (driver.requiresTransaction() && transaction == null)) {
transaction = beginTransaction(txType);
newTransaction = true;
}
T result = function.doInTransaction();
if (newTransaction && txManager.canCommit()) {
transaction.commit();
}
return result;
} catch (CypherException e) {
if (newTransaction && txManager.canRollback()) {
logger.warn("Error executing query : {} - {}. Rolling back transaction.", e.getCode(), e.getDescription());
transaction.rollback();
}
throw e;
} catch (Throwable e) {
if (newTransaction && txManager.canRollback()) {
logger.warn("Error executing query : {}. Rolling back transaction.", e.getMessage());
transaction.rollback();
}
throw driver.getExceptionTranslator().translateExceptionIfPossible(e);
} finally {
if (newTransaction && transaction != null && !transaction.status().equals(Transaction.Status.CLOSED)) {
transaction.close();
}
}
}
use of org.neo4j.ogm.transaction.Transaction in project neo4j-ogm by neo4j.
the class SatelliteIntegrationTest method shouldCommitLongTransaction.
@Test
public void shouldCommitLongTransaction() {
Long id;
try (Transaction tx = session.beginTransaction()) {
// load all
Collection<Satellite> satellites = session.loadAll(Satellite.class);
assertThat(satellites).hasSize(11);
Satellite satellite = satellites.iterator().next();
id = satellite.getId();
satellite.setName("Updated satellite");
// update
session.save(satellite);
session.clear();
// refetch
Satellite updatedSatellite = session.load(Satellite.class, id);
assertThat(updatedSatellite.getName()).isEqualTo("Updated satellite");
tx.commit();
}
session.clear();
// fetch - after commit should be changed
// note, that because we aren't starting a new tx, we will be given an autocommit one.
Satellite reloadedSatellite = session.load(Satellite.class, id);
assertThat(reloadedSatellite.getName()).isEqualTo("Updated satellite");
}
Aggregations