Search in sources :

Example 1 with DatastoreReaderWriter

use of com.google.cloud.datastore.DatastoreReaderWriter in project spring-cloud-gcp by spring-cloud.

the class DatastoreTemplateTests method performTransactionTest.

@Test
public void performTransactionTest() {
    DatastoreReaderWriter transactionContext = mock(DatastoreReaderWriter.class);
    when(this.datastore.runInTransaction(any())).thenAnswer((invocation) -> {
        TransactionCallable<String> callable = invocation.getArgument(0);
        return callable.run(transactionContext);
    });
    List<Entity> e1 = Collections.singletonList(this.e1);
    when(transactionContext.fetch(ArgumentMatchers.<Key[]>any())).thenReturn(e1);
    String finalResult = this.datastoreTemplate.performTransaction((datastoreOperations) -> {
        datastoreOperations.save(this.ob2);
        datastoreOperations.findById("ignored", TestEntity.class);
        return "all done";
    });
    assertThat(finalResult).isEqualTo("all done");
    verify(transactionContext, times(1)).put(ArgumentMatchers.<FullEntity[]>any());
    verify(transactionContext, times(2)).fetch((Key[]) any());
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Entity(com.google.cloud.datastore.Entity) DatastoreReaderWriter(com.google.cloud.datastore.DatastoreReaderWriter) FullEntity(com.google.cloud.datastore.FullEntity) Key(com.google.cloud.datastore.Key) Test(org.junit.Test)

Example 2 with DatastoreReaderWriter

use of com.google.cloud.datastore.DatastoreReaderWriter in project spring-cloud-gcp by spring-cloud.

the class DatastoreTemplate method computeReferencedField.

private <T> T computeReferencedField(BaseEntity entity, ReadContext context, DatastorePersistentProperty referenceProperty, String fieldName, Class<T> type) {
    T referenced;
    if (referenceProperty.isLazyLoaded()) {
        DatastoreReaderWriter originalTx = getDatastoreReadWriter();
        referenced = LazyUtil.wrapSimpleLazyProxy(() -> {
            if (getDatastoreReadWriter() != originalTx) {
                throw new DatastoreDataException("Lazy load should be invoked within the same transaction");
            }
            return (T) findReferenced(entity, referenceProperty, context);
        }, type, entity.getValue(fieldName));
    } else {
        referenced = (T) findReferenced(entity, referenceProperty, context);
    }
    return referenced;
}
Also used : DatastoreReaderWriter(com.google.cloud.datastore.DatastoreReaderWriter) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException)

Aggregations

DatastoreReaderWriter (com.google.cloud.datastore.DatastoreReaderWriter)2 Entity (com.google.cloud.datastore.Entity)1 FullEntity (com.google.cloud.datastore.FullEntity)1 Key (com.google.cloud.datastore.Key)1 Test (org.junit.Test)1 DatastoreDataException (org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException)1