Convert List Objects to/from JSON in Spring Rest API and Spring Data JPA


Use JAR files which are listed below:

antlr-2.7.7.jar
aopalliance-1.0.jar
asm-debug-all-3.2.jar
aspectjrt-1.8.5.jar
cglib-2.2.jar
commons-logging-1.2.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.10.Final.jar
hibernate-entitymanager-4.3.10.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.1.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
javax.persistence-2.0.0.jar
javax.servlet-api-3.1.0.jar
javax.servlet.jsp.jstl-1.2.2.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jcl-over-slf4j-1.7.10.jar
jstl-1.2.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.10.jar
spring-aop-4.1.5.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE.jar
spring-core-4.1.5.RELEASE.jar
spring-data-commons-1.10.0.RELEASE.jar
spring-data-jpa-1.8.0.RELEASE.jar
spring-expression-4.3.3.RELEASE.jar
spring-framework-bom-4.0.0.RELEASE.jar
spring-jdbc-4.0.9.RELEASE.jar
spring-orm-4.0.9.RELEASE.jar
spring-tx-4.0.9.RELEASE.jar
spring-web-4.0.6.RELEASE.jar
spring-webmvc-4.0.6.RELEASE.jar
taglibs-standard-impl-1.2.1.jar
xml-apis-1.0.b2.jar

Create a database with the name is learnspringrestfulwebservices. This database have a table: Products table

--
-- Table structure for table `products`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` decimal(10,1) NOT NULL,
  `quantity` int(11) NOT NULL,
  `status` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 1', '12.2', 2, 1);
INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 2', '6.5', 6, 1);
INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 3', '11.8', 8, 1);




Create Dynamic Web Project in Eclipse and add the below configuration to the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Spring Restful Web Services Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 					http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	 					http://www.springframework.org/schema/context
	 					http://www.springframework.org/schema/context/spring-context-4.0.xsd
	 					http://www.springframework.org/schema/data/jpa
						http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
	 					http://www.springframework.org/schema/mvc
	 					http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<context:component-scan base-package="demo.*" />

	<mvc:annotation-driven />

	<jpa:repositories base-package="demo.repositories" />

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/learnspringrestfulwebservices" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="demo.entities" />
		<property name="jpaVendorAdapter">
         	<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      	</property>
	</bean>

</beans>




Create entities package in server project. Create a entity class: Product.java as below

Product.java

package demo.entities;

import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "product")
public class Product{

	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private boolean status;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

}

The ProductRepository interface extends from CrudRepository interface of Spring Data JPA that provides CRUD operations for an entity.

package demo.repositories;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import demo.entities.Product;

@Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, Integer> {

}




The ProductService interface contains methods to interact with the database.

package demo.services;

import demo.entities.Product;

public interface ProductService {

	public Iterable<Product> findAll();

}

The ProductServiceImpl class implements methods from ProductService interfaces that contains methods to interact with the database.

package demo.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import demo.entities.Product;
import demo.repositories.ProductRepository;

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductRepository productRepository;

	@Override
	public Iterable<Product> findAll() {
		return productRepository.findAll();
	}

}

Create Rest API Controller provides application/json data for the client

package demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import demo.entities.Product;
import demo.services.ProductService;

@RestController
@RequestMapping("product")
public class ProductRestController {

	@Autowired
	private ProductService productService;

	@RequestMapping(
		value = "findall",
		method = RequestMethod.GET,
		produces = { MimeTypeUtils.APPLICATION_JSON_VALUE },
		headers = "Accept=application/json"
	)
	public ResponseEntity<Iterable<Product>> findAll() {
		try {
			return new ResponseEntity<Iterable<Product>>(productService.findAll(), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<Iterable<Product>>(HttpStatus.BAD_REQUEST);
		}

	}

}




Access Rest API Controller use the following url: http://localhost:8086/LearnSpringRestfulWebServices_Server/api/product/findall

Output

[
	{"id":1,"name":"name 1","price":12.2,"quantity":2,"status":true},
	{"id":2,"name":"name 2","price":6.5,"quantity":6,"status":false},
	{"id":3,"name":"name 3","price":11.8,"quantity":8,"status":true}
]

Create Java Project in Eclipse

Create entities package in Console Application. Create a entity class: Product.java as below

Product.java

package entities;

import java.math.BigDecimal;

public class Product {

	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private boolean status;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

}

DemoRestClientModel class contain methods call Web API

package models;

import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import entities.Product;

public class DemoRestClientModel {

	private String BASE_URL = "http://localhost:8086/LearnSpringRestfulWebServices_Server/api/product/";
	private RestTemplate restTemplate = new RestTemplate();

	public ResponseEntity<List<Product>> findAll() {
		try {
			return restTemplate.exchange(
						BASE_URL + "findall",
						HttpMethod.GET,
						null,
						new ParameterizedTypeReference<List<Product>>(){}
					);
		} catch (Exception e) {
			return null;
		}
	}

}




package main;

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import entities.Product;
import models.DemoRestClientModel;

public class Main {

	public static void main(String[] args) {

		DemoRestClientModel demoRestClientModel = new DemoRestClientModel();
		ResponseEntity<List<Product>> responseEntity = demoRestClientModel.findAll();
		if (responseEntity != null) {
			HttpStatus httpStatus = responseEntity.getStatusCode();
			System.out.println("Status Code: " + httpStatus);

			List<Product> products = responseEntity.getBody();
			System.out.println("Products List");
			for(Product product : products) {
				System.out.println("Id: " + product.getId());
				System.out.println("Name: " + product.getName());
				System.out.println("Price: " + product.getPrice());
				System.out.println("Quantity: " + product.getQuantity());
				System.out.println("Status: " + product.isStatus());
				System.out.println("===============================");
			}
		} else {
			System.out.println("Can not connect to find web method");
		}

	}

}
Status Code: 200
Products List
Id: 1
Name: name 1
Price: 12.2
Quantity: 2
Status: true
===============================
Id: 2
Name: name 2
Price: 6.5
Quantity: 6
Status: false
===============================
Id: 3
Name: name 3
Price: 11.8
Quantity: 8
Status: true
===============================