Illustration Image

Cassandra.Link

The best knowledge base on Apache Cassandra®

Helping platform leaders, architects, engineers, and operators build scalable real time data platforms.

7/9/2019

Reading time:2 min

Quick-start spring rest-api with Cassandra - Ankit Kumar Gupta - Medium

by John Doe

Step 2: Goto this downloaded folder and run this project to see everything is setup correctly.Step 3: Add Employee.java file. it is resource entity which also defines table in dbpackage com.example.demo.model;import org.springframework.data.cassandra.core.mapping.PrimaryKey;import org.springframework.data.cassandra.core.mapping.Table;import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NonNull;import lombok.Setter;@AllArgsConstructor@Getter @Setter@Tablepublic class Employee {@PrimaryKey private @NonNull String id;private @NonNull String firstName;private @NonNull String lastName;private @NonNull String email;}Step 4: Add EmployeeRepository.java, this will provide default implementations of actions possible with database.package com.example.demo.repository;import org.springframework.data.repository.CrudRepository;import com.example.demo.model.Employee;public interface EmployeeRepository extends CrudRepository<Employee, String> {}Step 5: Add EmployeeController.java, this will integrate our rest api with repository and perform the CRUD operations.package com.example.demo.controller;import java.util.ArrayList;import java.util.List;import java.util.Optional;import java.util.Random;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import com.example.demo.model.Employee;import com.example.demo.repository.EmployeeRepository;@RestControllerpublic class EmployeeController{@AutowiredEmployeeRepository employeeRepository;@GetMapping(value = "/healthcheck", produces = "application/json; charset=utf-8")public String getHealthCheck(){return "{ \"isWorking\" : true }";}@GetMapping("/employees")public List<Employee> getEmployees(){Iterable<Employee> result = employeeRepository.findAll();List<Employee> employeesList = new ArrayList<Employee>();result.forEach(employeesList::add);return employeesList;}@GetMapping("/employee/{id}")public Optional<Employee> getEmployee(@PathVariable String id){Optional<Employee> emp = employeeRepository.findById(id);return emp;}@PutMapping("/employee/{id}")public Optional<Employee> updateEmployee(@RequestBody Employee newEmployee, @PathVariable String id){Optional<Employee> optionalEmp = employeeRepository.findById(id);if (optionalEmp.isPresent()) {Employee emp = optionalEmp.get();emp.setFirstName(newEmployee.getFirstName());emp.setLastName(newEmployee.getLastName());emp.setEmail(newEmployee.getEmail());employeeRepository.save(emp);}return optionalEmp;}@DeleteMapping(value = "/employee/{id}", produces = "application/json; charset=utf-8")public String deleteEmployee(@PathVariable String id) {Boolean result = employeeRepository.existsById(id);employeeRepository.deleteById(id);return "{ \"success\" : "+ (result ? "true" : "false") +" }";}@PostMapping("/employee")public Employee addEmployee(@RequestBody Employee newEmployee){String id = String.valueOf(new Random().nextInt());Employee emp = new Employee(id, newEmployee.getFirstName(), newEmployee.getLastName(), newEmployee.getEmail());employeeRepository.save(emp);return emp;}}Step 6: update application.properties to have cassandra properties//server portserver.port = 8082//cassandra properiesspring.data.cassandra.keyspace-name=mykeyspacespring.data.cassandra.contact-points=localhostspring.data.cassandra.port=9042spring.data.cassandra.schema-action=create_if_not_existsNow run your project again as step 2 and perform CRUD operations.#get all employeescurl -X GET \http://localhost:8082/employees \-H 'Cache-Control: no-cache'#get employee by IDcurl -X GET \http://localhost:8082/employee/729280953 \-H 'Cache-Control: no-cache'#update employee by IDcurl -X PUT \http://localhost:8082/employee/729280953 \-H 'Cache-Control: no-cache' \-H 'Content-Type: application/json' \-d '{"id": "729280953","firstName": "ankit","lastName": "gupta","email": "testankit@gmail.com"}'#delete employee by IDcurl -X DELETE \http://localhost:8082/employee/980694165 \-H 'Cache-Control: no-cache' \-H 'Content-Type: application/x-www-form-urlencoded'#create employeecurl -X POST \http://localhost:8082/employee \-H 'Cache-Control: no-cache' \-H 'Content-Type: application/json' \-d '{"id": 3,"firstName": "ankit","lastName": "gupasd1","email": "test@gmail.com"}'Where next? you might want to read my other quick-start stories.

Illustration Image

Step 2: Goto this downloaded folder and run this project to see everything is setup correctly.

Step 3: Add Employee.java file. it is resource entity which also defines table in db

package com.example.demo.model;import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@AllArgsConstructor
@Getter @Setter
@Table
public class Employee {
@PrimaryKey
private @NonNull String id;
private @NonNull String firstName;
private @NonNull String lastName;
private @NonNull String email;
}

Step 4: Add EmployeeRepository.java, this will provide default implementations of actions possible with database.

package com.example.demo.repository;import org.springframework.data.repository.CrudRepository;import com.example.demo.model.Employee;public interface EmployeeRepository extends CrudRepository<Employee, String> {
}

Step 5: Add EmployeeController.java, this will integrate our rest api with repository and perform the CRUD operations.

package com.example.demo.controller;import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
@RestController
public class EmployeeController
{
@Autowired
EmployeeRepository employeeRepository;
@GetMapping(value = "/healthcheck", produces = "application/json; charset=utf-8")
public String getHealthCheck()
{
return "{ \"isWorking\" : true }";
}
@GetMapping("/employees")
public List<Employee> getEmployees()
{
Iterable<Employee> result = employeeRepository.findAll();
List<Employee> employeesList = new ArrayList<Employee>();
result.forEach(employeesList::add);
return employeesList;
}
@GetMapping("/employee/{id}")
public Optional<Employee> getEmployee(@PathVariable String id)
{
Optional<Employee> emp = employeeRepository.findById(id);
return emp;
}
@PutMapping("/employee/{id}")
public Optional<Employee> updateEmployee(@RequestBody Employee newEmployee, @PathVariable String id)
{
Optional<Employee> optionalEmp = employeeRepository.findById(id);
if (optionalEmp.isPresent()) {
Employee emp = optionalEmp.get();
emp.setFirstName(newEmployee.getFirstName());
emp.setLastName(newEmployee.getLastName());
emp.setEmail(newEmployee.getEmail());
employeeRepository.save(emp);
}
return optionalEmp;
}
@DeleteMapping(value = "/employee/{id}", produces = "application/json; charset=utf-8")
public String deleteEmployee(@PathVariable String id) {
Boolean result = employeeRepository.existsById(id);
employeeRepository.deleteById(id);
return "{ \"success\" : "+ (result ? "true" : "false") +" }";
}
@PostMapping("/employee")
public Employee addEmployee(@RequestBody Employee newEmployee)
{
String id = String.valueOf(new Random().nextInt());
Employee emp = new Employee(id, newEmployee.getFirstName(), newEmployee.getLastName(), newEmployee.getEmail());
employeeRepository.save(emp);
return emp;
}
}

Step 6: update application.properties to have cassandra properties

//server port
server.port = 8082
//cassandra properies
spring.data.cassandra.keyspace-name=mykeyspace
spring.data.cassandra.contact-points=localhost
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=create_if_not_exists

Now run your project again as step 2 and perform CRUD operations.

#get all employees
curl -X GET \
http://localhost:8082/employees \
-H 'Cache-Control: no-cache'
#get employee by ID
curl -X GET \
http://localhost:8082/employee/729280953 \
-H 'Cache-Control: no-cache'
#update employee by ID
curl -X PUT \
http://localhost:8082/employee/729280953 \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"id": "729280953",
"firstName": "ankit",
"lastName": "gupta",
"email": "testankit@gmail.com"
}'
#delete employee by ID
curl -X DELETE \
http://localhost:8082/employee/980694165 \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/x-www-form-urlencoded'
#create employee
curl -X POST \
http://localhost:8082/employee \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"id": 3,
"firstName": "ankit",
"lastName": "gupasd1",
"email": "test@gmail.com"
}'

Where next? you might want to read my other quick-start stories.

Related Articles

spring
angular
rest

GitHub - jhipster/jhipster-sample-app-cassandra: This is a sample application created with JHipster, with the Cassandra option

jhipster

3/7/2024

Checkout Planet Cassandra

Claim Your Free Planet Cassandra Contributor T-shirt!

Make your contribution and score a FREE Planet Cassandra Contributor T-Shirt! 
We value our incredible Cassandra community, and we want to express our gratitude by sending an exclusive Planet Cassandra Contributor T-Shirt you can wear with pride.

Join Our Newsletter!

Sign up below to receive email updates and see what's going on with our company

Explore Related Topics

AllKafkaSparkScyllaSStableKubernetesApiGithubGraphQl

Explore Further

cassandra