Continuing on with the Tech Tutorials Series . Rakesh is at again, does he sleep ?  He may be a cyborg. Well, hope this helps you coders out there with any Java Spring Hibernate Jersey JPA issues. He made it super easy, check it out…..

Objective

We will expose a database table ‘employee’ over REST API using Apache Jersey framework that provides implementation for JAX-RS, Spring framework to manage beans life cycle and dependencies of beans and Hibernate that provides the default JPA 2.0 implementation in Spring Data JPA. All of the components (Java Spring Hibernate Jersey JPA) will be used by the end of this tutorial.

I have used the Eclipse but you should be able use any other IDE like IntelliJ , MyEclipse etc.

Prerequisites for the – Java Spring Hibernate Jersey tutorial

  1. Download & Install MySQL – http://dev.mysql.com/downloads/
  2. Download & Install MySQL Workbench – https://www.mysql.com/products/workbench/

Implementation Steps – Java Spring Hibernate Jersey JPA

Following steps describes the overall process to have end to end implementation:

  1. Create Employee table in Database
  2. Import Maven dependencies for Spring JPA in pom.xml
  3. Configure Datasource properties in Spring to connect to database
  4. Create JPA entity bean for employee.
  5. Create DAO Interface to manage Employee entity
  6. Create Spring service to expose CRUD functionalities of Employee entity using DAO
  7. Create Employee REST resource to manage employee entity over HTTP


Database

1 Create Database Table

Open MySQL Workbench and go to INSTANCE → Start / Shutdown page and click start’Start Server’ button.

Screen Shot 2016-04-29 at 3.53.09 PM

Create a new schema with name ‘acme’.

Screen Shot 2016-04-29 at 3.53.34 PM

 

Create table Employee:

CREATE TABLE `acme`.`employee` (

`id` INT NOT NULL,

`firstname` VARCHAR(45) NOT NULL,

`lastname` VARCHAR(45) NOT NULL,

`department` VARCHAR(45) NOT NULL,

PRIMARY KEY (`id`));

Java

2. Add JPA & MySQL Dependencies

Add followings in pom.xml (at the root of the project level) to add Spring Data, REST, JPA and MySQL connector dependencies to project:

 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-rest</artifactId>

</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

 

Screen Shot 2016-04-29 at 3.55.34 PM

 

The Spring Boot JPA dependency will automatically add the hibernate dependencies as a default JPA implementation. MySQL connector dependency manages the connection to the backend MySQL server.

 

3. Configure DataSource Properties

Now that we have JPA – Hibernate dependencies in place, we need to provide the DataSource properties – URL and credentials to connect to MySQL server. These properties are configured in application.properties file under src/main/resource folder. Spring Boot by default looks into application.resource file to load all configuration properties during startup. We will also need to provide the MySQLdialect property along with datasource connection properties and other JPA specific properties in here. For example below i have also configured hibernate.show_sql property to print the actual SQL queries that will be executed by Spring during runtime.

 

spring.datasource.url=jdbc:mysql://<HOST>:<PORT>/<DATABASE>

spring.datasource.username=<USERNAME>

spring.datasource.password=<PASSWORD>

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.show_sql=true

 

spring.datasource.url=jdbc:mysql://localhost:3306/acme

spring.datasource.username=root

spring.datasource.password=admin

spring.jpa.properties.hibernate.dilect=org.hibernate.dialect.MySQL5Dialect

spring.jpa.properties.hibernate.show_sql=true

 

 

4. Create JPA entity bean

Create Employee entity class:

package com.spring.jersey.demo.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 long id;

           

            private String firstname;

            private String lastname;

            private String department;

           

            public long getId() {

                        return id;

            }

            public void setId(long id) {

                        this.id = id;

            }

 

            public String getDepartment() {

                        return department;

            }

            public void setDepartment(String department) {

                        this.department = department;

            }

            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;

            }

            @Override

            public String toString() {

                        return String.format(“Employee:{id:%d, firstName:%s, lastName:%s, department:%s}”,id,firstname,lastname,department );

            }

}

 

 

5. Create DAO Interface

With Spring Data JPA, you no longer need to create the full fledged DAO class to manage the entity. All you need to do is to create a JPA repository interface providing the entity type and its id type. Please refer to http://docs.spring.io/spring-data/jpa/docs/1.10.1.RELEASE/reference/html for further details.

 

package com.spring.jersey.demo.repo;

 

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

import com.spring.jersey.demo.model.Employee;

 

public interface EmployeeRepo extends JpaRepository<Employee, Long> {

 

}

 

6. Create Service

Next step is to create the Spring Service component to manage the Employee entity through EntityRepo dao class.

 

package com.spring.jersey.demo.service;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

 

import com.spring.jersey.demo.model.Employee;

import com.spring.jersey.demo.repo.EmployeeRepo;

 

@Service

public class EmployeeService {

 

            @Autowired

            private EmployeeRepo employeeRepo;

           

            /**

            * Retrieves <code>Employee</code> from repository.

            * @param id

            * @return <code>Employee</code>

            */

            @Transactional(readOnly=true)

            public Employee get(Long id){

                        return this.employeeRepo.findOne(id);

            }

           

            /**

            * Saves <code>Employee</code> in repository.

            */

            @Transactional

            public Employee save(Employee employee){

                        return this.employeeRepo.save(employee);

            }

           

            /**

            * Retrieves <code>Iterable<Employee></code> from repository.

            * @param id

            * @return <code>Employee</code>

            */

            @Transactional(readOnly=true)

            public Iterable<Employee> getAll(){

                        return this.employeeRepo.findAll();

            }

           

            /**

            * Deletes the <code>Employee</code> from repository.

            * @param employee

            */

            @Transactional

            public void delete(Employee employee){

                        this.employeeRepo.delete(employee);

            }

}

 

7. Create REST API

Create Jersey REST resource to expose the API to manage the Employee’s CRUD operations using the HTTP methods.

 

 

package com.spring.jersey.demo.rest;

 

import java.net.URI;

 

import javax.ws.rs.DELETE;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.PUT;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.Context;

import javax.ws.rs.core.MediaType;

import javax.ws.rs.core.Response;

import javax.ws.rs.core.Response.Status;

import javax.ws.rs.core.UriInfo;

 

import org.springframework.beans.factory.annotation.Autowired;

 

import com.spring.jersey.demo.model.Employee;

import com.spring.jersey.demo.service.EmployeeService;

 

@Path(“employees”)

public class EmployeeResource {

 

            @Autowired

            private EmployeeService employeeService;

           

            @Context

            private UriInfo uriinfo;

           

            /**

            * Retrieves a list of <code>Employee</code>

            * @return

            */

            @GET

            @Produces(MediaType.APPLICATION_JSON)

            public Iterable<Employee> get(){

                        return employeeService.getAll();

            }

           

            /**

            * Retrieves <code>Employee</code>

            * @param id

            * @return

            */

            @GET

            @Path(“/{id}”)

            @Produces(MediaType.APPLICATION_JSON)

            public Employee get(@PathParam(“id”) Long id){

                        return employeeService.get(id);

            }

           

            /**

            * Creates <code>Employee</code>

            * @param employee

            * @return

            */

            @POST

            public Response create(Employee employee){

                        Employee saved = this.employeeService.save(employee);

                        URI location = uriinfo.getAbsolutePathBuilder().path(“/”+saved.getId()).build();

                        return Response.created(location).build();

            }

           

            /**

            * Updates <code>Employee</code>

            * @param employee

            * @return

            */

            @PUT

            @Path(“/{id}”)

            public Response update(@PathParam(“id”) Long id, Employee employee){

                        employee.setId(id);

                        this.employeeService.save(employee);

                        return Response.noContent().build();

            }

           

            /**

            * Deletes <code>Employee</code>

            * @param employee

            * @return

            */

            @DELETE

            @Path(“/{id}”)

            public Response delete(@PathParam(“id”) Long id){

                        Employee employee = this.employeeService.get(id);

                        if(employee == null){

                                    return Response.status(Status.NOT_FOUND).build();

                        }else{

                                    this.employeeService.delete(employee);

                                    return Response.ok().build();

                        }

            }

}

 

8. Build & Run REST Service

Select “SpringJerseyDemo” project, right click and select ‘Run As → Maven Build (first Option)’.

Enter ‘spring-boot:run’ as Goals and click ‘Run’.

Screen Shot 2016-04-29 at 3.57.03 PM

Upon successful build, web application should be deployed and and started on embedded Tomcat server.

9. Execute REST API

Open any REST client to test the newly created Employee Service. I like FireFox – REST Client but you can use any other tool like POST for Chrome, CURL, SoapUI etc.

 

Create Employee:

 

URL: http://localhost:8080/employees

Method: POST

Request Headers: Content-Type:application/json

Request Body: {“firstname”:”John”,”lastname”:”Doe”,”department”:”THE-SMS-BLACKHOLE”}

Response: 201 – Created

Response Header: Location:http://localhost:8080/employees/3

 

Screen Shot 2016-04-29 at 3.57.57 PM

Retrieve Employee:

 

URL: http://localhost:8080/employees

Method: GET

Request Headers: Content-Type:application/json

Request Body: {“firstname”:”John”,”lastname”:”Doe”,”department”:”SMS”}

Response: 200 – OK

Response Body: {“id”:3,”firstname”:”John”,”lastname”:”Doe”,”department”:”SMS”,”version”:0}

Screen Shot 2016-04-29 at 3.58.47 PM

 

Update Employee:

URL: http://localhost:8080/employees/3

Method: PUT

Request Headers: Content-Type:application/json

Request Body:{“firstname”:”John”,”lastname”:”Doe”,”department”:”Fire”,”version”:0}

Response: 204 No Content

Screen Shot 2016-04-29 at 3.59.29 PM

Delete Employee:

URL: http://localhost:8080/employees/3

Method: DELETE

Response: 200 – OK (or 404 Not Found – for repeated call)

Screen Shot 2016-04-29 at 4.00.23 PM

 

10. Clone Spring-Jersey Demo

You can download the SpringJerseyDemo project from BitBucket: git@bitbucket.org:rbpraj15/springjerseydemo.git

References

Spring Framework: https://spring.io/projects

Apache Jersey: https://jersey.java.net/

Spring Data JPA: http://projects.spring.io/spring-data-jpa/

Eclipse: http://www.eclipse.org/downloads/

That concludes the Java Spring Hibernate Jersey JPA tutorial. I hope this helped. Please check back for future coding posts, as we will be adding one or two a month. Thanks for reading!!