Wednesday 11 December 2019

Spring Data REST: Hello World Application



Step 1: Create new maven project ‘springDataRest’.

Open Eclipse.

File -> New -> Other.


Search for Maven.


Select ‘Maven Project’.

Click on Next button.


Select check box ‘Create a simple project (skip archetype selection)’.

Click on Next button.

Give Group Id, Artifact Id as ‘springDataRest’ and version as 1.

Click on Finish button.

It create project structure like below.


Step 2: Update pom.xml with maven dependencies.

pom.xml
<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>springDataRest</groupId>
 <artifactId>springDataRest</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>



 <dependencies>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-rest</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-data-jpa</artifactId>
  </dependency>

  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
  </dependency>

 </dependencies>
</project>

Since I want to use H2 embedded database, I added h2 dependency.

Step 3: Create ‘application.properties’ file under src/main/resources.
application.properties
logging.level.root=WARN
logging.level.org.hibernate=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

Step 4: Create a package ‘com.sample.app.model’ and define Employee class like below.

Employee.java
package com.sample.app.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

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

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}

Step 5: Create a package ‘com.sample.app.repository’ and define EmployeeRepository interface like below.

EmployeeRepository.java    
package com.sample.app.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.sample.app.model.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer>{

}


Step 6: Define App.java class in com.sample.app package.

App.java    
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
 public static void main(String[] args) {

  SpringApplication.run(App.class, args);
 }
}

Total project structure look like below.

Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

Hibernate: 
    
    drop table employee if exists
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table employee (
       id integer not null,
        first_name varchar(255),
        last_name varchar(255),
        primary key (id)
    )
2019-07-10 09:33:55.156  WARN 11020 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

Open the url ‘http://localhost:8080/’ in browser, you can see all the REST endpoints exposed by spring data REST.




At the root of a Spring Data REST app is a profile link. It is used to explain the application semantics of a document with an application-agnostic media type (such as HTML, HAL, Collection+JSON, Siren, etc.)

Open the url 'http://localhost:8080/profile', in browser, you can see below screen.


Open the URL 'http://localhost:8080/profile/employees' to get the semantics of employees resource.

{
  "alps": {
    "version": "1.0",
    "descriptor": [
      {
        "id": "employee-representation",
        "href": "http://localhost:8080/profile/employees",
        "descriptor": [
          {
            "name": "firstName",
            "type": "SEMANTIC"
          },
          {
            "name": "lastName",
            "type": "SEMANTIC"
          }
        ]
      },
      {
        "id": "create-employees",
        "name": "employees",
        "type": "UNSAFE",
        "rt": "#employee-representation"
      },
      {
        "id": "get-employees",
        "name": "employees",
        "type": "SAFE",
        "descriptor": [
          {
            "name": "page",
            "type": "SEMANTIC",
            "doc": {
              "format": "TEXT",
              "value": "The page to return."
            }
          },
          {
            "name": "size",
            "type": "SEMANTIC",
            "doc": {
              "format": "TEXT",
              "value": "The size of the page to return."
            }
          },
          {
            "name": "sort",
            "type": "SEMANTIC",
            "doc": {
              "format": "TEXT",
              "value": "The sorting criteria to use to calculate the content of the page."
            }
          }
        ],
        "rt": "#employee-representation"
      },
      {
        "id": "update-employee",
        "name": "employee",
        "type": "IDEMPOTENT",
        "rt": "#employee-representation"
      },
      {
        "id": "patch-employee",
        "name": "employee",
        "type": "UNSAFE",
        "rt": "#employee-representation"
      },
      {
        "id": "delete-employee",
        "name": "employee",
        "type": "IDEMPOTENT",
        "rt": "#employee-representation"
      },
      {
        "id": "get-employee",
        "name": "employee",
        "type": "SAFE",
        "rt": "#employee-representation"
      }
    ]
  }
}

Create an employee
Method: POST
API: http://localhost:8080/employees
Body:
{
         "firstName" : "Bhadri",
         "lastName" : "Narayana"
}

Once you hit above request, you can see below response.

{
  "firstName": "Bhadri",
  "lastName": "Narayana",
  "_links": {
    "self": {
      "href": "http://localhost:8080/employees/1"
    },
    "employee": {
      "href": "http://localhost:8080/employees/1"
    }
  }
}

Get all the employees
Method: GET
API: http://localhost:8080/employees

Once you hit above request, you can see below kind of response.
{
  "_embedded": {
    "employees": [
      {
        "firstName": "Bhadri",
        "lastName": "Narayana",
        "_links": {
          "self": {
            "href": "http://localhost:8080/employees/1"
          },
          "employee": {
            "href": "http://localhost:8080/employees/1"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/employees{?page,size,sort}",
      "templated": true
    },
    "profile": {
      "href": "http://localhost:8080/profile/employees"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 1,
    "totalPages": 1,
    "number": 0
  }
}

Get specific employee details
Method: GET
API: http://localhost:8080/employees/1

Above request return employee information for the id 1.
{
  "firstName": "Bhadri",
  "lastName": "Narayana",
  "_links": {
    "self": {
      "href": "http://localhost:8080/employees/1"
    },
    "employee": {
      "href": "http://localhost:8080/employees/1"
    }
  }
}

Just like above, you can perform other HTTP requests like PUT, DELETE etc.,

You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment