Spring Boot DataRest Example @RepositoryRestResource

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see an essential crud operation on Spring Boot DataRest Example.
Spring Boot DataRest build on top of the Spring Data, and it’s taking the advantages of Spring HATEOAS. We can say that Spring Boot Data Rest combines the Spring Data and Spring HATEOS to provide the hypermedia-based Restful front end.
Spring Boot 2.1.4 RELEASE
Spring Boot Data JPA
Spring Boot DataRest
Lombok
MySQL connector
Java 8
Maven
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
As part of this example, we are going to implement a simple crud operation using spring datarest – here the data persisted in MySQL database.
We are configuring MySQL properties.
spring.datasource.driver-class-name:com.mysql.jdbc.Driver
spring.datasource.url:jdbc:mysql://localhost:3306/otp
spring.datasource.username:root
spring.datasource.password:1234

spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jooq.sql-dialect=org.hibernate.dialect.MySQL5Dialect

We are preparing Item domain object – representing an item table in the database.
package com.onlinetutorialspoint.domain;

import lombok.Data;
import lombok.NoArgsConstructor;

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

@Entity
@Data
@NoArgsConstructor
public class Item {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    private String category;
}
On the above Item class, we have used @Data and @NoArgsConstructor annotations to eliminate the boilerplate code like getters and setters, for more details on Lombok you can see this document.
The ItemRepository interface allows you to perform various CRUD operations on Item object. This repository gets CRUD operations from the PagingAndSortingRepository – it internally uses Spring Data Commons.
Apart from the basic CRUD operations, if we wanted to expose any domain related operations, you can always free to define your custom JPA operations or even use any JPQL operations inside the ItemRepository like below findByCategory().
package com.onlinetutorialspoint.repo;

import com.onlinetutorialspoint.domain.Item;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(path="items",collectionResourceRel = "items")
public interface ItemRepository extends PagingAndSortingRepository<Item,Long> {
    List<Item> findByCategory(@Param("category") String category);
}

@RepositoryRestResource creates HATEOAS service with Spring JPA and the operations will be exposed in HATEOAS format.
package com.onlinetutorialspoint;

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

@SpringBootApplication
public class SpringBootDataRestExampleApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootDataRestExampleApplication.class, args);
  }

}

$ mvn clean install
$ mvn spring-boot:run
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-05 13:44:12.317  INFO 556 --- [  restartedMain] c.o.SpringBootDataRestExampleApplication : Starting SpringBootDataRestExampleApplication on DESKTOP-RN4SMHT with PID 556 (D:\work\SpringBoot-DataRest-Example\target\classes started by Lenovo in D:\work\SpringBoot-DataRest-Example)
2019-05-05 13:44:12.323  INFO 556 --- [  restartedMain] c.o.SpringBootDataRestExampleApplication : No active profile set, falling back to default profiles: default
2019-05-05 13:44:12.491  INFO 556 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-05-05 13:44:12.491  INFO 556 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-05-05 13:44:16.069  INFO 556 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-05 13:44:16.218  INFO 556 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 126ms. Found 1 repository interfaces.
2019-05-05 13:44:17.287  INFO 556 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3afa984d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-05 13:44:17.346  INFO 556 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$ba7ae57f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-05 13:44:18.873  INFO 556 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-05-05 13:44:18.968  INFO 556 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-05 13:44:18.968  INFO 556 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-05-05 13:44:19.275  INFO 556 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-05 13:44:19.276  INFO 556 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6784 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-05-05 13:44:19.969  INFO 556 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-05 13:44:19.976  WARN 556 --- [  restartedMain] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-05-05 13:44:20.766  INFO 556 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-05 13:44:21.126  INFO 556 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
......
......

After running the application, go to http://localhost:8080/ then you would see the following JSON structure.
You can observe, there were two endpoints available /items with three different options (page, size, sort) and /profile which provides the application metadata.
Currently, there are no items in our database, let’s create some of them.
Now you can access all the available items using the http://localhost:8080/items/ endpoint.
{
    "_embedded": {
        "items": [
            {
                "name": "Thinking in Java",
                "category": "Books",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/items/1"
                    },
                    "item": {
                        "href": "http://localhost:8080/items/1"
                    }
                }
            },
            {
                "name": "Hibernate in Action",
                "category": "Books",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/items/2"
                    },
                    "item": {
                        "href": "http://localhost:8080/items/2"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/items{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/items"
        },
        "search": {
            "href": "http://localhost:8080/items/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}
On the above output, we can observe that, along with the items list, there is one more /search endpoint available. It is used to call the custom endpoints. Let’s try to access our custom endpoint getItemByCategory();
http://localhost:8080/items/search/findByCategory?category=Books
Done!
Spring Data Rest Document
Spring Boot Data JPA
Happy Learning 🙂

Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Kafka Producer Example
Spring Boot RabbitMQ Message Publishing Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot RabbitMQ Consumer Messages Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to set Spring Boot SetTimeZone
How to enable Swagger in Spring Boot Application
Spring Boot Hazelcast Cache Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example

Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Kafka Producer Example
Spring Boot RabbitMQ Message Publishing Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot RabbitMQ Consumer Messages Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to set Spring Boot SetTimeZone
How to enable Swagger in Spring Boot Application
Spring Boot Hazelcast Cache Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment