Spring Boot And Couch Base Demo
In this example we will store the data in couchbase using input form restful webservie using spring boot.
We will store the json data here i have created the bucket name demo and its contain the multiple document of order and here document id is refer to value of Key name Id.
JSON Data Structure :
{
"id": "201",
"order_id": "201",
"type": "order",
"customer_id": "24601",
"total_price": 255,
"lineitems": [
{
"item_id": 111,
"quantity": 3,
"base_price": 14,
"tax": 2,
"final_price": 15
},
{
"item_id": 222,
"quantity": 1,
"base_price": 12,
"tax": 1,
"final_price": 13
},
{
"item_id": 444,
"quantity": 2,
"base_price": 0,
"tax": 1,
"final_price": 0
}
]
}
Here document contains the subarray of line items which is another entity which contains the other item related fields.
In Couch base we have to create the bucket which name is : demo
And after that we have to store the document in demo bucket using manually for example as above mentioned JSON data or using POST request we can add document entry in the couchabse.
On demo bucket you have to create the primary index by below query for indexing purpose.
Couchbase is applying index on each entry present in bucket and fetch the relavant key value pair data.
N1ql Query to Create the index on demo bucket.
create primary index 'demo' on demo using GSI;
Follow below step to create the project.
1) Create the Spring Boot Project Using STS tool :
File -> New -> Spring Starter Project
Give Group , Artifact as per requirement.
2) Add dependencies of web and couchbase as shown in below screen shot.
after that click on finish your spring boot project will be created and it will contain the DemoApplication.java which is as below.
This one is our main class to run the application.
DemoApplication.java
package com.example.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.order</groupId>
<artifactId>order</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-couchbase</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
As you can see based on dependencies jars are downloaded and present under the maven dependencies.
3) To redefined the the configuration you have to put all parameters in application.properties which is present under the resource folder.
here i have define the property to connect local couchbase client and i have defined the server port for tomcat to 3000. ( By default it is 8080)
application.properties
spring.couchbase.bootstrap-hosts=127.0.0.1
spring.couchbase.bucket.name=demo
spring.data.couchbase.auto-index=true
server.port=3000
4)
All entities should be annotated with the @Document annotation
Also, every field in the entity should be annotated with the @Field annotation from the Couchbase SDK.
There is also a special @Id annotation which needs to be always in place. Best practice is to also name the property id.
String field with @Id to represent the Couchbase document key.
We use the @NotNull annotation to mark certain fields as required:
Based on the data format for the order entity which is mentioned above in form of JSON data.
we need to create the java class for the Order entity.
create the package : com.example.orders.order
under this package create class : Order.java
Order.java
package com.example.orders.order;
import java.util.Arrays;
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
@Document
public class Order {
@Id
private String id;
@Field
private String order_id;
@Field
private String type;
@Field
private String customer_id;
@Field
private int total_price;
@Field
private LineItems[] lineitems;
public Order()
{
}
public Order(String id,String order_id, String type, String customer_id, int total_price, LineItems[] lineitems) {
super();
this.id = id;
this.order_id=order_id;
this.type = type;
this.customer_id = customer_id;
this.total_price = total_price;
this.lineitems = lineitems;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCustomer_id() {
return customer_id;
}
public void setCustomer_id(String customer_id) {
this.customer_id = customer_id;
}
public int getTotal_price() {
return total_price;
}
public void setTotal_price(int total_price) {
this.total_price = total_price;
}
public LineItems[] getLineitems() {
return lineitems;
}
public void setLineitems(LineItems[] lineitems) {
this.lineitems = lineitems;
}
@Override
public String toString() {
return "Order [id=" + id + ", order_id=" + order_id + ", type=" + type + ", customer_id=" + customer_id
+ ", total_price=" + total_price + ", lineitems=" + Arrays.toString(lineitems) + "]";
}
}
4) Now as per JSON document order contains the lineitems array so create the LineItems.java under the package : com.example.orders.order
LineItems.java
package com.example.orders.order;
import com.couchbase.client.java.repository.annotation.Field;
public class LineItems {
@Field
private int item_id;
@Field
private int quantity;
@Field
private int base_price;
@Field
private float tax;
@Field
private float final_price;
public LineItems() {
}
public LineItems(int item_id, int quantity, int base_price, float tax, float final_price) {
super();
this.item_id = item_id;
this.quantity = quantity;
this.base_price = base_price;
this.tax = tax;
this.final_price = final_price;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getBase_price() {
return base_price;
}
public void setBase_price(int base_price) {
this.base_price = base_price;
}
public float getTax() {
return tax;
}
public void setTax(float tax) {
this.tax = tax;
}
public float getFinal_price() {
return final_price;
}
public void setFinal_price(float final_price) {
this.final_price = final_price;
}
@Override
public String toString() {
return "LineItems [item_id=" + item_id + ", quantity=" + quantity + ", base_price=" + base_price + ", tax="
+ tax + ", final_price=" + final_price + "]";
}
}
5) To Create the repository create the interface and extends it with CouchbaseRepository<Order, String>
Spring Data Couchbase provides the same built-in queries and derived query mechanisms as other Spring Data modules such as JPA.
For @ViewIndexed annotation required the index view name as per couch base functionality view should be created.
As per given example viewName = "all" should be created in Indexes -> Views link of couch base client.
@ViewIndexed
This annotation lets you define the name of the design document and View name as well as a custom map and reduce function.
@N1qlPrimaryIndexed
This annotation makes sure that the bucket associated to the current repository will have a N1QL primary index.
create the OrderRepository interface under the new package : com.example.orders.repository
OrderRepository.java
package com.example.orders.repository;
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.ViewIndexed;
import org.springframework.data.couchbase.repository.CouchbaseRepository;
import com.example.orders.order.Order;
@N1qlPrimaryIndexed
@ViewIndexed(designDoc = "order", viewName = "all")
public interface OrderRepository extends CouchbaseRepository<Order, String> {
}
6) now create the service layer which is using the OrderRepository bean to perform the CRUD operation
Crate the OrderService.java under the new package : com.example.orders.service
OrderService.java
package com.example.orders.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.couchbase.client.deps.com.fasterxml.jackson.core.JsonParseException;
import com.couchbase.client.deps.com.fasterxml.jackson.databind.JsonMappingException;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.transcoder.JacksonTransformers;
import com.example.orders.order.Order;
import com.example.orders.repository.OrderRepository;
@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public List<Order> findOrderByOrderId(String order_id)
{
List<Order> orders = new ArrayList<Order>();
Order order = null;
String statement = "select order_id, type, customer_id, total_price, lineitems from demo where order_id='" + order_id + "' ";
N1qlQuery q = N1qlQuery.simple(statement);
Cluster cluster = CouchbaseCluster.create("127.0.0.1");
Bucket bucket = cluster.openBucket("demo");
JsonObject rowJson = null;
for (N1qlQueryRow row : bucket.query(q)) {
rowJson = row.value();
try {
order = JacksonTransformers.MAPPER.readValue(rowJson.toString(), Order.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
orders.add(order);
}
return orders;
}
public List<Order> getAllOrder() {
List<Order> orders = new ArrayList<>();
orders = (List<Order>) orderRepository.findAll();
return orders;
}
public List<Order> findAll() {
List<Order> orders = new ArrayList<Order>();
Order order = null;
String statement = "select order_id, type, customer_id, total_price, lineitems from demo";
N1qlQuery q = N1qlQuery.simple(statement);
Cluster cluster = CouchbaseCluster.create("127.0.0.1");
Bucket bucket = cluster.openBucket("demo");
JsonObject rowJson = null;
for (N1qlQueryRow row : bucket.query(q)) {
rowJson = row.value();
try {
order = JacksonTransformers.MAPPER.readValue(rowJson.toString(), Order.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
orders.add(order);
}
return orders;
}
public Order getOrder(String order_id) {
return orderRepository.findOne(order_id);
}
public void addOrder(Order order) {
orderRepository.save(order);
}
public void updateOrder(Order order) {
orderRepository.save(order);
}
public void deleteOrder(String id) {
orderRepository.delete(id);
}
}
Here we are handling the rest request which we are initiating using the postman.
OrderController.java
package com.example.orders.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.orders.order.LineItems;
import com.example.orders.order.Order;
import com.example.orders.service.OrderService;
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping(value="/orders" )
public List<Order> getAllOrder()
{
return orderService.findAll();
}
@RequestMapping(value="/orders/{order_id}" )
public Order getOrderByOrderId(@PathVariable("order_id") String order_id)
{
// return orderService.findAllOrderByOrderId(order_id);
return orderService.getOrder(order_id);
}
@RequestMapping(value="/order/{order_id}")
public List<Order> getOrderdataByOrderId(@PathVariable("order_id") String order_id)
{
return orderService.findOrderByOrderId(order_id);
}
@PostMapping(value="/order")
public void addOrder(@RequestBody Order order)
{
orderService.addOrder(order);
}
@PutMapping(value="/order/{id}")
public void updateOrder(@RequestBody Order order ,@PathVariable String id)
{
orderService.updateOrder(order);
}
@DeleteMapping(value="/order/{id}")
public void deleteOrder(@RequestBody Order order ,@PathVariable String id)
{
orderService.deleteOrder(id);
}
}
Below is the screen shot of GET request based on the order id key.
GET request : http://localhost:3000/order/1010
In this example we will store the data in couchbase using input form restful webservie using spring boot.
We will store the json data here i have created the bucket name demo and its contain the multiple document of order and here document id is refer to value of Key name Id.
JSON Data Structure :
{
"id": "201",
"order_id": "201",
"type": "order",
"customer_id": "24601",
"total_price": 255,
"lineitems": [
{
"item_id": 111,
"quantity": 3,
"base_price": 14,
"tax": 2,
"final_price": 15
},
{
"item_id": 222,
"quantity": 1,
"base_price": 12,
"tax": 1,
"final_price": 13
},
{
"item_id": 444,
"quantity": 2,
"base_price": 0,
"tax": 1,
"final_price": 0
}
]
}
Here document contains the subarray of line items which is another entity which contains the other item related fields.
In Couch base we have to create the bucket which name is : demo
And after that we have to store the document in demo bucket using manually for example as above mentioned JSON data or using POST request we can add document entry in the couchabse.
On demo bucket you have to create the primary index by below query for indexing purpose.
Couchbase is applying index on each entry present in bucket and fetch the relavant key value pair data.
N1ql Query to Create the index on demo bucket.
create primary index 'demo' on demo using GSI;
Follow below step to create the project.
1) Create the Spring Boot Project Using STS tool :
File -> New -> Spring Starter Project
Give Group , Artifact as per requirement.
2) Add dependencies of web and couchbase as shown in below screen shot.
after that click on finish your spring boot project will be created and it will contain the DemoApplication.java which is as below.
This one is our main class to run the application.
DemoApplication.java
package com.example.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.order</groupId>
<artifactId>order</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-couchbase</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
As you can see based on dependencies jars are downloaded and present under the maven dependencies.
3) To redefined the the configuration you have to put all parameters in application.properties which is present under the resource folder.
here i have define the property to connect local couchbase client and i have defined the server port for tomcat to 3000. ( By default it is 8080)
application.properties
spring.couchbase.bootstrap-hosts=127.0.0.1
spring.couchbase.bucket.name=demo
spring.data.couchbase.auto-index=true
server.port=3000
4)
All entities should be annotated with the @Document annotation
Also, every field in the entity should be annotated with the @Field annotation from the Couchbase SDK.
There is also a special @Id annotation which needs to be always in place. Best practice is to also name the property id.
String field with @Id to represent the Couchbase document key.
We use the @NotNull annotation to mark certain fields as required:
Based on the data format for the order entity which is mentioned above in form of JSON data.
we need to create the java class for the Order entity.
create the package : com.example.orders.order
under this package create class : Order.java
Order.java
package com.example.orders.order;
import java.util.Arrays;
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
@Document
public class Order {
@Id
private String id;
@Field
private String order_id;
@Field
private String type;
@Field
private String customer_id;
@Field
private int total_price;
@Field
private LineItems[] lineitems;
public Order()
{
}
public Order(String id,String order_id, String type, String customer_id, int total_price, LineItems[] lineitems) {
super();
this.id = id;
this.order_id=order_id;
this.type = type;
this.customer_id = customer_id;
this.total_price = total_price;
this.lineitems = lineitems;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCustomer_id() {
return customer_id;
}
public void setCustomer_id(String customer_id) {
this.customer_id = customer_id;
}
public int getTotal_price() {
return total_price;
}
public void setTotal_price(int total_price) {
this.total_price = total_price;
}
public LineItems[] getLineitems() {
return lineitems;
}
public void setLineitems(LineItems[] lineitems) {
this.lineitems = lineitems;
}
@Override
public String toString() {
return "Order [id=" + id + ", order_id=" + order_id + ", type=" + type + ", customer_id=" + customer_id
+ ", total_price=" + total_price + ", lineitems=" + Arrays.toString(lineitems) + "]";
}
}
4) Now as per JSON document order contains the lineitems array so create the LineItems.java under the package : com.example.orders.order
LineItems.java
package com.example.orders.order;
import com.couchbase.client.java.repository.annotation.Field;
public class LineItems {
@Field
private int item_id;
@Field
private int quantity;
@Field
private int base_price;
@Field
private float tax;
@Field
private float final_price;
public LineItems() {
}
public LineItems(int item_id, int quantity, int base_price, float tax, float final_price) {
super();
this.item_id = item_id;
this.quantity = quantity;
this.base_price = base_price;
this.tax = tax;
this.final_price = final_price;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getBase_price() {
return base_price;
}
public void setBase_price(int base_price) {
this.base_price = base_price;
}
public float getTax() {
return tax;
}
public void setTax(float tax) {
this.tax = tax;
}
public float getFinal_price() {
return final_price;
}
public void setFinal_price(float final_price) {
this.final_price = final_price;
}
@Override
public String toString() {
return "LineItems [item_id=" + item_id + ", quantity=" + quantity + ", base_price=" + base_price + ", tax="
+ tax + ", final_price=" + final_price + "]";
}
}
5) To Create the repository create the interface and extends it with CouchbaseRepository<Order, String>
Spring Data Couchbase provides the same built-in queries and derived query mechanisms as other Spring Data modules such as JPA.
For @ViewIndexed annotation required the index view name as per couch base functionality view should be created.
As per given example viewName = "all" should be created in Indexes -> Views link of couch base client.
@ViewIndexed
This annotation lets you define the name of the design document and View name as well as a custom map and reduce function.
@N1qlPrimaryIndexed
This annotation makes sure that the bucket associated to the current repository will have a N1QL primary index.
create the OrderRepository interface under the new package : com.example.orders.repository
OrderRepository.java
package com.example.orders.repository;
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.ViewIndexed;
import org.springframework.data.couchbase.repository.CouchbaseRepository;
import com.example.orders.order.Order;
@N1qlPrimaryIndexed
@ViewIndexed(designDoc = "order", viewName = "all")
public interface OrderRepository extends CouchbaseRepository<Order, String> {
}
6) now create the service layer which is using the OrderRepository bean to perform the CRUD operation
Crate the OrderService.java under the new package : com.example.orders.service
OrderService.java
package com.example.orders.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.couchbase.client.deps.com.fasterxml.jackson.core.JsonParseException;
import com.couchbase.client.deps.com.fasterxml.jackson.databind.JsonMappingException;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.transcoder.JacksonTransformers;
import com.example.orders.order.Order;
import com.example.orders.repository.OrderRepository;
@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public List<Order> findOrderByOrderId(String order_id)
{
List<Order> orders = new ArrayList<Order>();
Order order = null;
String statement = "select order_id, type, customer_id, total_price, lineitems from demo where order_id='" + order_id + "' ";
N1qlQuery q = N1qlQuery.simple(statement);
Cluster cluster = CouchbaseCluster.create("127.0.0.1");
Bucket bucket = cluster.openBucket("demo");
JsonObject rowJson = null;
for (N1qlQueryRow row : bucket.query(q)) {
rowJson = row.value();
try {
order = JacksonTransformers.MAPPER.readValue(rowJson.toString(), Order.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
orders.add(order);
}
return orders;
}
public List<Order> getAllOrder() {
List<Order> orders = new ArrayList<>();
orders = (List<Order>) orderRepository.findAll();
return orders;
}
public List<Order> findAll() {
List<Order> orders = new ArrayList<Order>();
Order order = null;
String statement = "select order_id, type, customer_id, total_price, lineitems from demo";
N1qlQuery q = N1qlQuery.simple(statement);
Cluster cluster = CouchbaseCluster.create("127.0.0.1");
Bucket bucket = cluster.openBucket("demo");
JsonObject rowJson = null;
for (N1qlQueryRow row : bucket.query(q)) {
rowJson = row.value();
try {
order = JacksonTransformers.MAPPER.readValue(rowJson.toString(), Order.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
orders.add(order);
}
return orders;
}
public Order getOrder(String order_id) {
return orderRepository.findOne(order_id);
}
public void addOrder(Order order) {
orderRepository.save(order);
}
public void updateOrder(Order order) {
orderRepository.save(order);
}
public void deleteOrder(String id) {
orderRepository.delete(id);
}
}
7) now create the controller layer which is using the OrderService bean to perform the CRUD operation
To handle the rest call and send the response based on operation.
Crate the OrderController.java under the new package : com.example.orders.controllerTo handle the rest call and send the response based on operation.
Here we are handling the rest request which we are initiating using the postman.
OrderController.java
package com.example.orders.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.orders.order.LineItems;
import com.example.orders.order.Order;
import com.example.orders.service.OrderService;
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping(value="/orders" )
public List<Order> getAllOrder()
{
return orderService.findAll();
}
@RequestMapping(value="/orders/{order_id}" )
public Order getOrderByOrderId(@PathVariable("order_id") String order_id)
{
// return orderService.findAllOrderByOrderId(order_id);
return orderService.getOrder(order_id);
}
@RequestMapping(value="/order/{order_id}")
public List<Order> getOrderdataByOrderId(@PathVariable("order_id") String order_id)
{
return orderService.findOrderByOrderId(order_id);
}
@PostMapping(value="/order")
public void addOrder(@RequestBody Order order)
{
orderService.addOrder(order);
}
@PutMapping(value="/order/{id}")
public void updateOrder(@RequestBody Order order ,@PathVariable String id)
{
orderService.updateOrder(order);
}
@DeleteMapping(value="/order/{id}")
public void deleteOrder(@RequestBody Order order ,@PathVariable String id)
{
orderService.deleteOrder(id);
}
}
8) As our project is ready now we can perform GET, POST , PUT , DELETE operation using restful webservices.
Below are the urls you can use to perform different request using POSTMAN tool
To Add the Order : POST request : http://localhost:3000/order
Here in request body part you have to pass the JSON data structure of order which i have mentioned in beginning.
Get All Orders : GET Request : http://localhost:3000/orders
Get Order Based on Order Id : GET Request : http://localhost:3000/order/201
here 201 is order id you have to pass order id based on your data stored in couch base db.
Change the request for Order Id : PUT Request: http://localhost:3000/order/1010
Here in request body part you have to pass the existing JSON data structure of order.
here 1010 is order id you have to pass order id based on your data stored in couch base db.
Delete the request for Order Id : DELETE Request: http://localhost:3000/order/1010
here 1010 is order id you have to pass order id based on your data stored in couch base db.
Below is the screen shot of GET request based on the order id key.
GET request : http://localhost:3000/order/1010
Happy End!!!!!!!!
Enjoy Coding.

Comments
Post a Comment