DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • RESTful API Example With Spring Data REST and JPA Hibernate Many To Many Extra Columns
  • Spring Boot - Microservice - Spring Data REST and HATEOAS Integration
  • Your Guide to GraphQL [Tutorials and Articles]
  • Getting Started With Spring Boot and Spring Data REST

Trending

  • The Emergence of Cloud-Native Integration Patterns in Modern Enterprises
  • Continuous Integration vs. Continuous Deployment
  • How To Deploy Helidon Application to Kubernetes With Kubernetes Maven Plugin
  • Unleashing the Power of Microservices With Spring Cloud
  1. DZone
  2. Data Engineering
  3. Data
  4. Exporting Spring Data JPA Repositories as REST Services using Spring Data REST

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

Siva Prasad Reddy Katamreddy user avatar by
Siva Prasad Reddy Katamreddy
·
Mar. 07, 14 · Tutorial
Like (0)
Save
Tweet
Share
28.99K Views

Join the DZone community and get the full member experience.

Join For Free

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.

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>


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.

@Entity
@Table(name = "USERS")
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Integer id;
@Column(name = "username", nullable = false, unique = true, length = 50)
private String userName;
@Column(name = "password", nullable = false, length = 50)
private String password;
@Column(name = "firstname", nullable = false, length = 50)
private String firstName;
@Column(name = "lastname", length = 50)
private String lastName;
@Column(name = "email", nullable = false, unique = true, length = 50)
private String email;
@Temporal(TemporalType.DATE)
private Date dob;
private boolean enabled=true;
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="user_id")
private Set<Role> roles = new HashSet<>();
@OneToMany(mappedBy = "user")
private List<Contact> contacts = new ArrayList<>();
//setters and getters
}
@Entity
@Table(name = "ROLES")
public class Role implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Integer id;
@Column(name="role_name",nullable=false)
private String roleName;
//setters and getters
}
@Entity
@Table(name = "CONTACTS")
public class Contact implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "contact_id")
private Integer id;
@Column(name = "firstname", nullable = false, length = 50)
private String firstName;
@Column(name = "lastname", length = 50)
private String lastName;
@Column(name = "email", nullable = false, unique = true, length = 50)
private String email;
@Temporal(TemporalType.DATE)
private Date dob;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
//setters and getters
}


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.

package com.sivalabs.springdatarest.web.config;
import javax.servlet.Filter;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.sivalabs.springdatarest.config.AppConfig;
public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] { AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses()
{
return new Class<?>[] { WebMvcConfig.class, RepositoryRestMvcConfiguration.class };
}
@Override
protected String[] getServletMappings()
{
return new String[] { "/rest/*" };
}
@Override
    protected Filter[] getServletFilters() {
       return new Filter[]{
       new OpenEntityManagerInViewFilter()
       };
    } 
}



Create Spring Data JPA repositories for JPA entities.

public interface UserRepository extends JpaRepository<User, Integer>
{
}
public interface RoleRepository extends JpaRepository<Role, Integer>
{
}
public interface ContactRepository extends JpaRepository<Contact, Integer>
{
}


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.RELEASE\bin>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/

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/spring-data-rest-demo/rest/users/{?page,size,sort}",
            "templated": true
        },
        "search": {
            "href": "http://localhost:8080/spring-data-rest-demo/rest/users/search"
        }
    },
    "_embedded": {
        "users": [
            {
                "userName": "admin",
                "password": "admin",
                "firstName": "Administrator",
                "lastName": null,
                "email": "admin@gmail.com",
                "dob": null,
                "enabled": true,
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1"
                    },
                    "roles": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/roles"
                    },
                    "contacts": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/contacts"
                    }
                }
            },
            {
                "userName": "siva",
                "password": "siva",
                "firstName": "Siva",
                "lastName": null,
                "email": "sivaprasadreddy.k@gmail.com",
                "dob": null,
                "enabled": true,
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2"
                    },
                    "roles": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/roles"
                    },
                    "contacts": {
                        "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/contacts"
                    }
                }
            }
        ]
    },
    "page": {
        "size": 20,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}
You can find the source code at https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/spring-data-rest-demo
For more Info on Spring Rest Shell: https://github.com/spring-projects/rest-shell
REST Web Protocols Spring Data Spring Framework Data (computing)

Published at DZone with permission of Siva Prasad Reddy Katamreddy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • RESTful API Example With Spring Data REST and JPA Hibernate Many To Many Extra Columns
  • Spring Boot - Microservice - Spring Data REST and HATEOAS Integration
  • Your Guide to GraphQL [Tutorials and Articles]
  • Getting Started With Spring Boot and Spring Data REST

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: