Spring Boot Getting Started with Google Data Store.

Spring Boot Getting Started with Google Data Store.

Google Data Store also  know Firebase Data Store is a No-SQL data base which store data as documents like MongoDB its similar like  Amazon's Dynamo DB or Azure Cosmos DB provided with other cloud competitor. Spring Boot provides starter package for Google data Store so writing and saving Entities is pretty Straight forward.

Before getting started we need google's gcloud shell and  gcloud emulators datastore installed in our local system. so datastore emulator  works like local database for testing and querying.

Lets begin with integrating Google Data Store with Spring

  1. Start the data store emalulator and override system env with this key value DATASTORE_EMULATOR_HOST=localhost:<port>.

  2. Add following Dependency in the pom in the spring boot application pom.

  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-data-datastore</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter</artifactId>
            <version>1.1.3.RELEASE</version>
            <type>pom</type>
        </dependency>
  1. Add these in application properties files for Gcp to detect the configuration.
spring.cloud.gcp.datastore.enabled=true
spring.cloud.gcp.datastore.project-id=<project-id>

4 Add this @EnableDatastoreRepositories annotation in main Spring class

5 Create Sample pojo like the example below

@Entity
public class BrowserHistory {
    @Id
    Long id;
    String name;
    String url;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
  1. Create repository for the entity sample repo looks like this
public interface BrowserHistoryRepo extends DatastoreRepository<BrowserHistory,Long> {
}
  1. Saving the result example
Class
.....
 @Autowired
 BrowserHistoryRepo browserHistoryRepo;
 ....
  BrowserHistory history = new BrowserHistory();
        history.setName("test");
        history.setUrl("http://working");
        browserHistoryRepo.save(history);
  1. Using spring cloud data started supports @Query annotation or writing function in iterface for retrival
  2. Writing GQL
Class
    ....
     @Autowired
    Datastore datastore;
    ...
    Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY,"select * from browserHistory").build();
        QueryResults<Entity> results = datastore.run(query);

The result will be in iterator pattern value can be access with while loop in java.