0

I am trying to use gcp datastore sample but I would like initialize repository manually. Something like SimpleJpaRepository in another SO. Is it possible to initialize DatastoreRepository ?

Example with JPA repository one can simply do :

EmployeeRepository employeeRepository = new JpaRepositoryFactory(entityManager) .getRepository(EmployeeRepository.class);

entityManager can be injected via hibernate session factory. All entity classes can be registered to the registry of session factory.

Now , in order to initialize/register EmployeeRepository : public interface EmployeeRepository extends DatastoreRepository

Note: The environment where the code will run does not have auto-wiring/annotations support.

Ankit
  • 57
  • 7
  • what do you mean with initializing DatastoreRepository manually? you mean creating a database and then the entities? if it is so, you can do it programmatically using the normal methods. – asbovelw May 13 '20 at 15:31

1 Answers1

0

I am able to get it to work by using below :

DatastoreFactory datastoreFactory = new DefaultDatastoreFactory();
Supplier<Datastore> datastore = () -> datastoreFactory.create(DatastoreOptions.getDefaultInstance());


//Register Datastore Entity classes
DatastoreMappingContext datastoreMappingContext = new DatastoreMappingContext();
datastoreMappingContext.setInitialEntitySet(new HashSet<>(Arrays.asList(Employee.class)));

ObjectToKeyFactory objectToKeyFactory = new DatastoreServiceObjectToKeyFactory(datastore);

DatastoreEntityConverter datastoreEntityConverter = new DefaultDatastoreEntityConverter(datastoreMappingContext, objectToKeyFactory);
DatastoreOperations datastoreOperations = new DatastoreTemplate(datastore,datastoreEntityConverter, datastoreMappingContext, objectToKeyFactory);

EmployeeRepository employeeRepository  = new SimpleDatastoreRepository<>(datastoreOperations, Employee.class);
employeeRepository.count(); // findAll() etc
Ankit
  • 57
  • 7