Spring Data REST XML Configuration Example

This example shows how to expose entities as rest services using Spring Data REST API and XML Configuration. This example uses H2 in memory database.

Please refer to similar example using java configuration.

This is implemented by configuring Spring Data Rest’s RepositoryRestDispatcherServlet, an extension of DispatcherServlet in web.xml.

Spring Data REST combines the features of Spring Data JPA and Spring HATEOAS.

Entity (Task.java)


package com.idodevjobs.example.entity;

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

@Entity
public class Task {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int     id;
	private String  name;
	private String  description;
	private String  priority;
	private String  status;
	private boolean archived;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPriority() {
        return priority;
    }

    public void setPriority(String priority) {
        this.priority = priority;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public boolean isArchived() {
        return archived;
    }

    public void setArchived(boolean archived) {
        this.archived = archived;
    }

    @Override
    public String toString() {
        return "Task{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", priority='" + priority + '\'' +
                ", status='" + status + '\'' +
                ", archived=" + archived +
                '}';
    }
}


Repository (TaskRepository.java)


package com.idodevjobs.example.repository;

import com.idodevjobs.example.entity.Task;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource
public interface TaskRepository extends CrudRepository<Task, Integer> {

	List<Task> findByArchivedTrue();
	List<Task> findByArchivedFalse();
	List<Task> findByStatus(@Param("status") String taskStatus);

}


Spring Config (applicationContext.xml)


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.idodevjobs.example" />

    <jpa:repositories base-package="com.idodevjobs.example.repository" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.idodevjobs.example.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:annotation-driven/>

    <jdbc:embedded-database id="dataSource" type="H2"/>

</beans>

Webapp Config (web.xml)


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

</web-app>

Maven (pom.xml)


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.idodevjobs.example</groupId>
    <artifactId>spring-data-rest-xml-config-example</artifactId>
    <name>spring-data-rest-xml-config-example</name>
    <properties>
        <spring.version>4.0.5.RELEASE</spring.version>
        <spring.data.jpa.version>1.6.0.RELEASE</spring.data.jpa.version>
        <spring.data.rest.webmvc.version>2.1.1.RELEASE</spring.data.rest.webmvc.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <slf4j.version>1.7.7</slf4j.version>
        <h2.version>1.4.179</h2.version>
        <junit.version>4.11</junit.version>
    </properties>

    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring.data.jpa.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
            <version>${spring.data.rest.webmvc.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-data-rest-xml-config-example</finalName>
    </build>

</project>

Testing

Do a mvn clean install and deploy the war on apache-tomcat.

Using any rest client like POSTMAN, the services can be tested by hitting the below url. As we have included Jackson JSON libraries, the data format used is JSON.

http://localhost:8080/spring-data-rest-xml-config-example/api/tasks

Spring Data Rest supports HATEOAS and it also provides all the methods that Spring Data repository provides as REST services. We can also define custom methods in repository which will automatically be exposed as REST services.

PS: This post uses some code from this and this.

Advertisements
This entry was posted in java and tagged , , , , , , . Bookmark the permalink.

5 Responses to Spring Data REST XML Configuration Example

  1. Pingback: Spring Data REST Java Configuration Example | iDoDevJobs

  2. Bio Hazard says:

    Thank you very much for sharing this! There are not a lot of Spring Data REST tutorial that use XML configuration, and this really helps!!

    Like

  3. Pingback: Spring Data REST Java Configuration Example | iDoDevJobs

  4. Pingback: Develop a simple RESTful Webservices using Apache CXF and Spring Framework – Part I | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s