Exporting Spring Data JPA Repositories as REST Services using Spring Data REST

Spring Data modules provides various modules to work with various types of datasources like RDBMS, NOSQL stores etc in unified way. In my previous article  SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig I have explained how to configure Spring Data JPA using JavaConfig.

Now in this post let us see how we can use Spring Data JPA repositories and export JPA entities as REST endpoints using Spring Data REST.

First let us configure spring-data-jpa and spring-data-rest-webmvc dependencies in our pom.xml.

Make sure you have latest released versions configured correctly, otherwise you will encounter the following error:
java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler

Create JPA entities.

Configure DispatcherServlet using AbstractAnnotationConfigDispatcherServletInitializer.

Observe that we have added RepositoryRestMvcConfiguration.class to getServletConfigClasses() method.
RepositoryRestMvcConfiguration is the one which does the heavy lifting of looking for Spring Data Repositories and exporting them as REST endpoints.

https://gist.github.com/sivaprasadreddy/9303094 /]

Create Spring Data JPA repositories for JPA entities.

That’s it. Spring Data REST will take care of rest of the things.

You can use spring Rest Shell https://github.com/spring-projects/rest-shell or Chrome’s Postman Addon to test the exported REST services.

D:rest-shell-1.2.1.RELEASEbin>rest-shell
http://localhost:8080:>

Now we can change the baseUri using baseUri command as follows:
http://localhost:8080:>baseUri http://localhost:8080/spring-data-rest-demo/rest/
http://localhost:8080/spring-data-rest-demo/rest/>

http://localhost:8080/spring-data-rest-demo/rest/>list
rel         href
======================================================================================
users       http://localhost:8080/spring-data-rest-demo/rest/users{?page,size,sort}
roles       http://localhost:8080/spring-data-rest-demo/rest/roles{?page,size,sort}
contacts    http://localhost:8080/spring-data-rest-demo/rest/contacts{?page,size,sort}

Note: It seems there is an issue with rest-shell when the DispatcherServlet url mapped to “/” and issue list command it responds with “No resources found”.

http://localhost:8080/spring-data-rest-demo/rest/>get users/

RESTEasy Tutorial Part 3 – Exception Handling

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling

Exception Handling is an obvious requirement while developing software application. If any error occured while processing user request we should show the user an error page with details like brief exception message, error code(optional), hints to correct the input and retry(optional) and actual root cause(optional). This is applicable to RESTful web services also.

But putting try-catch-finally blocks all around the code is not a good practice. We should design/code in such a way that if there is any unrecoverable error occured then the code should throw that exception and there should an exception handler to catch those exceptions and extract the error details and give a proper error response to the client with all the error details.

RESTEasy provides such ExceptionHandler mechanism which simplifies the ExceptionHandling process.

In this part I will show you how we can use RESTEasy’s ExceptionHandlers to handle Exceptions.

Step#1: Create Application Specific Exceptions.

Step#2: Create ExceptionHandlers by implementing ExceptionMapper interface.

Step#3: Update UserResource.getUserXMLById() method to validate user input and throw respective exceptions.

Step#4: Test the UserResource.getUserXMLById() service method by issueing following requests.


Important things to note:
As Spring is creating the necessary objects we should let Spring know about @Provider classes to get them registered with RESTEasy. We can do this in two ways.

a)Annotate Provider classes with @Component

b)Using component-scan’s include-filter.

<context:component-scan base-package=”com.sivalabs.springdemo”>
         <context:include-filter expression=”javax.ws.rs.ext.Provider” type=”annotation”/>
</context:component-scan>

RESTEasy Tutorial Part-2: Spring Integration

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy provides support for Spring integration which enables us to expose Spring beans as RESTful WebServices.

Step#1: Configure RESTEasy+Spring dependencies using Maven.

Step#2: Configure RESTEasy+Spring in web.xml


		
   
    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
  
  
    org.jboss.resteasy.plugins.spring.SpringContextLoaderListener
  
  
    Resteasy
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
  
  
    Resteasy
    /rest/*
  
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
    resteasy.servlet.mapping.prefix
    /rest
  

  
        resteasy.scan
        false
    

Step#3: Create a Spring Service class UserService and update UserResource to use UserService bean.

Step#4: Same JUnit TestCase to test the REST Webservice described in Part-1.

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.
2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*
3. While using Spring integration set resteasy.scan to false or don’t configure resteasy.scan parameter at all.
Otherwise you may get REST Resource instances(UserResource) from RestEasy instead of Spring container. While running JUnit Tests I observed this random behavior.

4. You should register REST Resource as Spring bean by annotating with @Component or @Service.

RESTEasy Tutorial Part-1: Basics

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy is a JAX-RS implementation from JBoss/RedHat and is in-built in JBoss 6 onwards.
Here I am going to show you how to develop a Simple RESTful Web Services application using RESTEasy and JBossAS7.1.1.FINAL.

Step#1: Configure RESTEasy dependencies using Maven.

Step#2: Configure RESTEasy in web.xml

Step#3: Create User domain class, MockUserTable class to store User objects in-memory for testing purpose and UserResource class to expose CRUD operations on User as RESTful webservices.

Step#6: JUnit TestCase to test the REST Webservice.

Step#7: To test the REST service we can use the REST Client Tool. 
You can download REST Client Tool at http://code.google.com/a/eclipselabs.org/p/restclient-tool/

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.

2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*


3. Keep visiting my blog 🙂