Thursday 3 October 2019

Spring Boot + Hibernate + JPA + Restful WebServices + Maven Example Project

Spring Boot + Hibernate + JPA  + Restful WebServices + Maven



In this post ,we will help you create a complete spring boot application with hibernate and JPA implementation. We have used restful websercices for rest api call instead of spring rest api.

The structure of the project will be like,



Add maven dependency into pom.xml,

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

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>


<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/javax.persistence -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.2.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jersey -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>

</dependencies>

Create a POJO for test_data1 table  as follows ,

package com.testdata;

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

@Entity
@Table(name="test_data1")
public class TestData1 {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="test1id")
private Long test1id;

@Column(name="test1data")
private String test1data;

public Long getTest1id() {
return test1id;
}

public void setTest1id(Long test1id) {
this.test1id = test1id;
}

public String getTest1data() {
return test1data;
}

public void setTest1data(String test1data) {
this.test1data = test1data;
}

}

@Entity  - to specify it as a POJO class ( to access table or entity).
@Table  - to specify the table name that we are going to access.
@Id - to specify the primary key.
@GeneratedValue - to specify it as auto incremented value.
 @Column - to specify for which column in table the specified field will be used.

Create a repository named TestRepository which extends JPA repository to perform all database related operations.

package com.testdata;

import java.util.List;

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

public interface TestRepository extends JpaRepository<TestData1, Long> {

List<TestData1> findAll();
}

TestRepository   if it extends JPA repository can get all the methods defined in JPA repository.
TestData1 - is the pojo name for the specified table.
Long - the primary key datatype of the given table. 
Note - JPA repository extends CRUD repository which can get all the methods in  CRUD repository  like (Save , Delete etc...)


Then create a Service class which will be used to process all the data that you get from repository (All code logic will go here).

package com.testdata;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

@Service
public class TestData1Service {

@Autowired
TestRepository testRepository;

public Map<String, String> getdata() {
List<TestData1> test1data = testRepository.findAll();

Map<String, String> map = null;

for (int i = 0; i < test1data.size(); i++) {

map = new HashMap<>();

map.put("id", String.valueOf(test1data.get(i).getTest1id()));
map.put("data", test1data.get(i).getTest1data());
}

return map;
}

}

The above method in service class will get all data from test_data1 table and process it to become a json using HashMap.


Then finally create a  resource file for api calls with front-end and (or) with other external or internal applications using Restful webservices.

package com.testdata1;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

import com.testdata.TestData1Service;

@Path("/test")
@Component
public class TestData1Resource {

@Autowired
TestData1Service testData1Service;

@GET
@Path("/testData")
@Produces(MediaType.APPLICATION_JSON)
public Response getData() {

try {
return Response.ok(testData1Service.getdata()).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}

}

@Path - to specify the path of rest api.
@GET - to specify it as GET method.
@Produces(MediaType.APPLICATION_JSON) - to tell the return type should be of type JSON. 
@Component - to create and manage the bean by spring IOC container. 
@Autowired  - to get the reference of bean created by IOC container. 


For restful webservices , we need a file called jersy config to register the resource files for exxternal communication.

package com.config;

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

import com.testdata1.TestData1Resource;

@Configuration
@ApplicationPath("/")
public class JerseyConfig extends ResourceConfig {

JerseyConfig() {
registerTestData1Resource();
}

private void registerTestData1Resource() {
register(TestData1Resource.class);
}
}

register is the method present in ResourceConfig  class to register all the resource files to jersy .




Your application.properties file will be like ,

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root
server.port = 8070

server.port  - is the port used to run application
spring.datasource.url - to connect with the database at 3306 port in localhost with database named 'test'.
spring.datasource.username - database username 
spring.datasource.password - database password 


your Application.java file will be like,

package com;

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

@SpringBootApplication
public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

@SpringBootApplication  - tells that this is a spring boot application .


No comments:

Post a Comment

Unity Top Download

Latest post

An Introduction to Hybris from basics

An Introduction to Hybris from basics:  -- ecommerce site and PCM(Product content Management) solutions. eg. croma website.  -- having sear...

Popular posts