Spring Data Gemfire Example

In the previous example, we demonstrated how we can connect to a Relational/SQL database with Spring using the Spring Data. In this example we will see how we can connect the Gemfire using the Spring Data.

Gemfire is a highly scalable, low-latency, in-memory data management platform which stores data in the key-value form. The data maybe persisted onto the disk. Gemfire provides it own set of tools for data management – gfsh, a command line utility tool. But it offers very limited set of control and maneuverability. Spring provides better control through Spring Gemfire module which simplify the Gemfire Data Grid configuration.

So let’s start with an example to see how we can achieve the same.

The first step is to setup the GemFire Cache. The Cache can be setup using cache.xml or with the help of Spring Data GemFire’s XML namespace. However, the preferred way is to use the Spring IoC as it offers a number of benefits from the configuration as well the ease of development point of view.The configuration advantages include Spring FactoryBean pattern, modular XML configuration, property placeholders so that the configuration can be externalized etc. The development benefits include auto code completions, real time validations when using intelligent IDEs like eclipse and STS. Given the above benefits, we shall proceed with the example by bootstrapping the GemFire Data Grid through Spring Container.

So we proceed to define the gfshBean.xml which contains the basic configuration information for the GemFire Data Grid.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/gemfire http://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire.xsd">
	<!--Spring Components Scan-->
	<context:component-scan base-package="com.jcg.examples"></context:component-scan>

	<!--GemFire Cache -->
	<gfe:cache />

	<!--Region for being used by the Record Bean -->
	<gfe:replicated-region persistent="true" id="record" />

	<!--Scan for annotated GemFire Repositories-->
	<gfe-data:repositories base-package="com.jcg.examples" />


  • Line 11: Basic configuration to create a GemFire Cache.
  • Line 15: Create a GemFire Region with type as replicated. The persistent marks the data to be maintained on the disk as well. The default value is false. It needs to be written to disk when fail-safety is required.
  • Line 18: Scan the packages for initializing GemFire Bean Repositories.

Now that the GemFire Data Grid is configured we can create a PoJo to map to the GemFire Region.


package com.jcg.examples.bean;

import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.gemfire.mapping.Region;

public class RecordBean implements Serializable

		private static final long serialVersionUID = 3209342518270638000L;

		private String recordId;

		private String recordString;

                public RecordBean(){}

		public RecordBean(String recordId, String recordString)
				this.recordId = recordId;
				this.recordString = recordString;

		public String getRecordId()
				return recordId;

		public void setRecordId(String recordId)
				this.recordId = recordId;

		public String getRecordString()
				return recordString;

		public void setRecordString(String recordString)
				this.recordString = recordString;

		public String toString()
				return "RecordBean [Record Id=" + recordId + ", Record String=" + recordString + "]";


The annotation @Region("record") is required to tell the Container as to which Region the PoJo maps to, same as we map a PoJo to a table in a relational Database.

The @Id annotation marks the property that is to be used as Cache Key for retrieving the values.

The @PersistenceConstructor constructor tells the Spring Container as to which constructor should be used for creation of entities. When the PoJo has only one constructor the annotation is not required. The toString method is used to display the bean properties.

Now that the PoJo is ready we need to create the DAO layer. The RecordRepository interface does the job of this.


package com.jcg.examples.repository;

import java.util.Collection;

import org.springframework.data.gemfire.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.jcg.examples.bean.RecordBean;

 * @author Chandan Singh
public interface RecordRepository extends CrudRepository<RecordBean, Integer> {

	RecordBean findByRecordId(String recordId);
	@Query("SELECT * FROM /record")  
  Collection<RecordBean> myFindAll();  

The Spring Data provides a number of inbuilt method for manipulating the Data. We need not write the queries for basic data manipulation and reading. It is achieved by extending the CrudRepository and declaring the proper Generics as per the PoJo.In case the Developer is not satisfied with the existing method, he can create his own method by specifying the Query using the @query annotation.

The Spring IoC Container creates an instance of this Repository and makes it available to be used as a Bean.

Now that all is set, let’s run the application and test out the code! Here’s Application class that loads the XML file to instantiate the Spring Container and power up the GemFire Data Grid.


package com.jcg.examples.main;

import java.util.Iterator;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.jcg.examples.bean.RecordBean;
import com.jcg.examples.repository.RecordRepository;

public class Application

		public static void main(String[] args)
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); 
			context.setConfigLocation(new ClassPathResource("resources/gfshBean.xml").getPath());
			RecordRepository recordRepository = context.getBean(RecordRepository.class);
		        RecordBean recordBean = new RecordBean("1", "One");
			System.out.println("Successful run!!");
			RecordBean recordBeanFetched = recordRepository.findByRecordId("2");
			System.out.println("The Fetched record bean is "+recordBeanFetched);
			Iterable<RecordBean> recordCollection = recordRepository.myFindAll();
			System.out.println("RecordBeans List : ");
			for (Iterator<RecordBean> iterator = recordCollection.iterator(); iterator.hasNext();)
		        	 RecordBean recordBeannew = (RecordBean) iterator.next();

We create instances of the RecordBean and save them using the RecordRepository we configured earlier. Then we proceed to fetch the saved data in various ways. The data gets persisted onto the disk, so even if we run the Application Class multiple times the record returns the data saved in the previous runs.

Here’s the sample output of the program :

Successful run!!
The Fetched record bean is RecordBean [Record Id=2, Record String=Two]
RecordBeans List : 
RecordBean [Record Id=3, Record String=Three]
RecordBean [Record Id=2, Record String=Two]
RecordBean [Record Id=1, Record String=One]
[info 2015/07/18 23:22:28.298 IST  tid=0xb] VM is exiting - shutting down distributed system

Download the Source Code

Here we demonstrated how to configure and manage a GemFire Data Repository using Spring Data.

You can download the source code of this example here: GemFIreSpringData.zip

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Back to top button