Skip to main content

Redis Basic CRUD

We have seen how to setup on your linux machine here , now we will see how to perform basic CRUD operations using Spring Data & Redis server

We will be creating a simple application that would persist an employee information into redis database. You will be needing certain JARs like jedis.jar, spring-data-redis.jar etc details of which you can download and view at https://github.com/meta-magic/RedisCRUDexample.git 
First of all we will be creating the Employee entity, plz note that we are using the Serializable interface which automatically mapps the objects against the key.


Employee.java



import java.io.Serializable;
public class Employee implements Serializable
{
private static final long serialVersionUID = -8243145429438016231L;
public enum Gender{Male, Female}
private String id;
private String name;
private Gender gender;
private int age;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Gender getGender()
{
return gender;
}
public void setGender(Gender gender)
{
this.gender = gender;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
...
}

Then, we will be defining the Repository interface and its implementation

EmployeeRepository.java
import java.util.Map;
import com.metamagicglobal.examples.redis.entity.Employees;
public interface EmployeeRepository
{
public void addEmployee(Employees employee);
public Employees getEmployeeById(String id);
public Map<Object, Object> getAllEmployees();
void updateEmployee(Employees employee);
public void delEmployeeById(String id);
}
EmployeeRepositoryImpl uses the RedisTemplate to communicate with the Redis Server. Since we are using Hash based Operations, we are using the Redistemplate opsForHash(). The method returns an instance of HashOperations class


EmployeeRepositoryImpl.java

public class EmployeeRepositoryImpl implements EmployeeRepository
{
private RedisTemplate<String, Employees> redisTemplate;
private static String EMP_KEY = "Employees";
public RedisTemplate<String, Employees> getRedisTemplate()
{
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Employees> redisTemplate)
{
this.redisTemplate = redisTemplate;
}
@Override
public void addEmployee(Employees emp)
{
this.redisTemplate.opsForHash().put(EMP_KEY, emp.getId(), emp);
}
@Override
public Employees getEmployeeById(String id)
{
return (Employees)this.redisTemplate.opsForHash().get(EMP_KEY, id);
}
@Override
public Map<Object,Object> getAllEmployees()
{
return this.redisTemplate.opsForHash().entries(EMP_KEY);
}
@Override
public void delEmployeeById(String id)
{
this.redisTemplate.opsForHash().delete(EMP_KEY,id);
}
@Override
public void updateEmployee(Employees emp) {
// TODO Auto-generated method stub
this.redisTemplate.opsForHash().put(EMP_KEY, emp.getId(), emp);
}
}
The RedisTemplate injected into the EmployeeRepositoryImpl class by the Spring BeanFactory. The RedisTemplate requires the JedisConnectionFactory instance from the Jedis JAR. Next we inject the RedisTemplate instance into the EmployeeRepositoryImpl bean as a reference. We can also use @Autowired to configure the same and add the component-scan directive in the XML.

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Redis Connection Factory -->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:use-pool="true" />
<!-- Redis Template Configuration-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory" />
<bean id="empRepo" class="com.metamagicglobal.examples.redis.repository.EmployeeRepositoryImpl">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
</beans>



We shall test the code using the repository calls on employee object.

EmployeeTest.java


public class EmployeeTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new ClassPathResource("resources/spring-config.xml").getPath());
EmployeeRepository empRepo = (EmployeeRepository) context.getBean("empRepo");
Employees emp = new Employees();
emp.setId("101");
emp.setAge(55);
emp.setGender(Gender.Female);
emp.setName("Jenny Joe");
empRepo.addEmployee(emp);
...
Map<Object, Object> empMap = empRepo.getAllEmployees();
System.out.println("Display All Employees");
System.out.println(empMap);
System.out.println("Find Employee by ID : " + empRepo.getEmployeeById("103"));
emp3.setAge(40);
empRepo.updateEmployee(emp3);
System.out.println("Employee after update : " + empRepo.getEmployeeById("103"));
System.out.println("Deleting Employee ID : 102 ");
empRepo.delEmployeeById("102");
System.out.println("Display All Employees");
empMap = empRepo.getAllEmployees();
System.out.println(empMap);
context.close();
}
}

Output

Display All Employees

{103=
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=25, 102=
Employee - ID=102, Name=John Doe, Gender=Male, Age=60, 101=
Employee - ID=101, Name=Jenny Joe, Gender=Female, Age=55}
Find Employee by ID  : 
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=25
Employee after update  : 
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=40
Deleting Employee ID : 2 
Display All Employees
{103=
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=40, 101=

Employee - ID=101, Name=Jenny Joe, Gender=Female, Age=55}

Comments

Popular posts from this blog

Redis Installation Steps

“ Redis is an in-memory key-value store known for its flexibility, performance, and wide language support” Inorder to install redis on your machine you need ubuntu 16.4 and a non-root user with sudo privileges to perform the administrative functions required for this process. Download and Extract the Source Code Create a tmp directory cd /tmp Download the latest stable version of Redis curl -O http://download.redis.io/redis-stable.tar.gz untar tar xzvf redis-stable.tar.gz Move into the Redis source directory structure that was just extracted cd redis-stable Build and Install Redis Now, we can compile the Redis binaries by typing make After the binaries are compiled, run the test suite to make sure everything was built correctly. You can do this by typing: make test This will typically take a few minutes to run. Once it is complete, you can install the binaries onto the system by typing: sudo

CRUD in MongoDB & Spring Data

Now, since we have already been introduced to mongo and its server is setup. We shall now move on to performing basic CRUD operations. Lets take a use case example of ‘Company’ database that stores employee information.  We wish to store employee name, email address, age and multiple addresses. Traditionally in RDBMS we would create an Employee table and Address Table having foreign key reference to ‘employee id ‘ Incase of NoSQL, we will be creating Employee documnet which will have store employee information like name, email, age and an array of employes address. Following is a snippet of the schema defined { "name" : "", "email" : "", "age" : “”, "address" : [ ... ] } Thus to begin with, we will first define the entities. We have employee as an aggregate root entity that stores list of address having 1-M relatioship. Address Entity is represend as @Embeddable as it is embaded in another aggregate root entity. Employee is