Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
rajnish_tiwari2
Advisor
Advisor
0 Kudos
This is the continuation of previous blog (blog series), In this blog series will be explaining about rest api implementation using spring jax-rs,

Introduction

You can implement REST call through JPAContext using the Spring APIs, when creating a JPA application three things are required to build your foundation. First you need an entity class, which simply contains a method that has your fields (variables) as well as your getter and setter methods.In entity class basically we will be creating the mapping of columns, Above each of the variables you can add annotations for keys, column names, not null attributes, and relationships. The entity object is simply a POJO class which has a @Entity annotation. Then we need to include the Spring-servlet.xml will be stored under WEB-INF folder also you need to add the dependency in POM.xml

1.1 Entity class as Shown in section 3.4 in blog part-1

1.2. Adding the dependency in POM
<properties>
<spring.version>4.0.5.RELEASE</spring.version>
<eclipselink.version>2.6.0</eclipselink.version>
<log4j.version>1.2.17</log4j.version>
<jdk.version>1.7</jdk.version>
<olingo.version>2.0.6</olingo.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.16.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.2.1</version>
</dependency>

1.3. Adding the spring-servlet.xml file under WEB-INF folder
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jolokia="http://www.jolokia.org/jolokia-spring/schema/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.jolokia.org/jolokia-spring/schema/config
http://www.jolokia.org/jolokia-spring/schema/config/jolokia-config.xsd">

<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<context:component-scan base-package="com.sap.sample.restServices" />
<mvc:annotation-driven />
<beans>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="sampleTest"/>
</bean>
</beans>
</beans>

1.4. Spring-servlet has to be included in web.xml file, code snippet has to added

 
	<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/rest/api/*</url-pattern>
</servlet-mapping>

1.5 Now create class where using JPAEntitymanager establish a connection, basically to connect to database

 
@RestController
@RequestMapping("/v1")
public class RestServices {
private EntityManagerFactory emf;
final static Logger LOGGER = LoggerFactory.getLogger(RestServices.class);
final static Logger LOGGER1 = LoggerFactory.getLogger("sampleRestServices");

@PersistenceUnit
public void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}

@RequestMapping(value = "/emp", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Status> fetch() {
EntityManager em = this.emf.createEntityManager();
HttpHeaders httpHeaders = new HttpHeaders();
try {
Query query = em.createQuery("from Employee as p");
return new ResponseEntity(new Status("Success","Records Returned",query.getResultList()), httpHeaders, HttpStatus.ACCEPTED);
}
finally {
if (em != null) {
em.close();
}
}
}
@RequestMapping(value = "/emp", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Status> create(@RequestBody List<Employee> empLst) {
EntityManager em = this.emf.createEntityManager();
HttpHeaders httpHeaders = new HttpHeaders();
try {
em.getTransaction().begin();
for(Employee obj:empLst){
em.persist(obj);
}
em.getTransaction().commit();
return new ResponseEntity(new Status("Success","Records Created"), httpHeaders, HttpStatus.ACCEPTED);
}
finally {
if (em != null) {
em.close();
}
}
}
}

1.6  Along with the above RestServices class, there is status class, which you can use to return the response of the Object, below the sample of code
public class Status {
private String messageType;
private String message;
private Object result;

public Status(String messageType,String message,Object result) {
this.messageType=messageType;
this.message=message;
this.result=result;
}
public Status(String messageType,String message) {
// TODO Auto-generated constructor stub
this.messageType=messageType;
this.message=message;
this.result=null;
}

public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
}

1.7.1 Test the rest services in Advance rest client tool (a chrome extension)

Below e.g. show the data insert in Employee table, status code is 202, which means data is inserted successfully.


Now to check the GET method in Advance rest client tool, the data which you have inserted in above call, circled in below screen shots,


I have not implemented the PUT, DELETE method but it can be implemented in similar way.

Hope this blog help you to implement the REST API using Spring mvc. The REST API and OData Olingo 2.0 implementation can exists together and maintained in the same applications. In next blog I will be explaining about the limitations of Olingo OData 2.0. 

https://blogs.sap.com/2017/02/06/olingo-odata-2.0-limitations/

Few of my other blogs about the logging in HCP as mentioned below

https://blogs.sap.com/2016/12/02/logging-in-hcp-cloud-foundry-with-java-and-tomee-using-slf4j-logbac...