• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Boot CRUDRepository Example- Spring Data JPA

July 17, 2017 by javainterviewpoint Leave a Comment

In this article, we will learn how to integrate Spring Data JPA into our Spring Boot application. We will be extending CrudRepository which in turn extends the Repository interface and hence there is no need for implementing our own methods. We will be creating a Student management application and store the details using Oracle database.

Spring Data REST takes the features of Spring HATEOAS and Spring Data JPA and combines them together automatically. Spring Data REST configuration is defined in a class called RepositoryRestMvcConfiguration and that class can just be imported into your application’s configuration

Creating table

Create STUDENT Table, simply Copy and Paste the following SQL query in the query editor to get the table created.

CREATE TABLE "STUDENT" 
 ( "ID" NUMBER(10,0) NOT NULL ENABLE, 
   "NAME" VARCHAR2(255 CHAR), 
   "AGE" NUMBER(10,0) NOT NULL ENABLE, 
   PRIMARY KEY ("ID")
 );

 insert into "STUDENT" values (1,'JIP1',11);
 insert into "STUDENT" values (2,'JIP2',22);
 insert into "STUDENT" values (3,'JIP3',33);
 insert into "STUDENT" values (4,'JIP4',44);

Spring Boot CRUDRepository Example

Folder Structure:

Spring Boot CRUDRepository Example

  1. Create a simple Maven Project “SpringBoot” by selecting maven-archetype-quickstart  and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.javainterviewpoint</groupId>
    	<artifactId>SpringBoot</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.1.RELEASE</version>
    	</parent>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-rest</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.oracle</groupId>
    			<artifactId>ojdbc14</artifactId>
    			<version>11.2.0</version>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    				<configuration>
    					<source>1.7</source>
    					<target>1.7</target>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
  3. Create the Java classes App.java,Student.java and StudentRepository.java under com.javainterviewpoint folder.

Other interesting articles which you may like …

  • Spring Boot Hello World Example with Maven
  • Spring Boot Hello World Example in Eclipse
  • How to Create Deployable WAR | Spring Boot | SpringBootServletInitializer
  • Spring Boot – How to Change Embedded Tomcat default port
  • Fix missing src/main/java folder in Eclipse Maven Project
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services

The spring-boot-starter-parent is a special starter, it provides useful Maven defaults. We will be using two using two additional Spring Boot Starters spring-boot-starter-data-jpa, spring-boot-starter-data-rest apart from spring-boot-starter-parent.

Dependency Tree

$ mvn dependency:tree
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBoot 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ SpringBoot ---
[INFO] com.javainterviewpoint:SpringBoot:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-data-rest:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] |  |  +- org.springframework:spring-core:jar:4.3.6.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-web:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.5.1.RELEASE:compile
[INFO] |  |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.11:compile
[INFO] |  |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.11:compile
[INFO] |  |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.11:compile
[INFO] |  |  +- org.hibernate:hibernate-validator:jar:5.3.4.Final:compile
[INFO] |  |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  |  \- com.fasterxml:classmate:jar:1.3.3:compile
[INFO] |  |  +- org.springframework:spring-web:jar:4.3.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-webmvc:jar:4.3.6.RELEASE:compile
[INFO] |  |     \- org.springframework:spring-expression:jar:4.3.6.RELEASE:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.6:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.6:compile
[INFO] |  \- org.springframework.data:spring-data-rest-webmvc:jar:2.6.0.RELEASE:compile
[INFO] |     +- org.springframework.data:spring-data-rest-core:jar:2.6.0.RELEASE:compile
[INFO] |     |  +- org.springframework.hateoas:spring-hateoas:jar:0.23.0.RELEASE:compile
[INFO] |     |  +- org.springframework.plugin:spring-plugin-core:jar:1.2.0.RELEASE:compile
[INFO] |     |  \- org.atteo:evo-inflector:jar:1.2.1:compile
[INFO] |     +- org.slf4j:slf4j-api:jar:1.7.22:compile
[INFO] |     \- org.slf4j:jcl-over-slf4j:jar:1.7.22:compile
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.3.6.RELEASE:compile
[INFO] |  |  \- org.aspectj:aspectjweaver:jar:1.8.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat:tomcat-jdbc:jar:8.5.11:compile
[INFO] |  |  |  \- org.apache.tomcat:tomcat-juli:jar:8.5.11:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:4.3.6.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.0.11.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.21.0-GA:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] |  +- org.hibernate:hibernate-entitymanager:jar:5.0.11.Final:compile
[INFO] |  +- javax.transaction:javax.transaction-api:jar:1.2:compile
[INFO] |  +- org.springframework.data:spring-data-jpa:jar:1.11.0.RELEASE:compile
[INFO] |  |  +- org.springframework.data:spring-data-commons:jar:1.13.0.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-orm:jar:4.3.6.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-context:jar:4.3.6.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-tx:jar:4.3.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:4.3.6.RELEASE:compile
[INFO] |  \- org.springframework:spring-aspects:jar:4.3.6.RELEASE:compile
[INFO] \- com.oracle:ojdbc14:jar:11.2.0:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:50 min
[INFO] Finished at: 2017-07-14T12:33:28+05:30
[INFO] Final Memory: 18M/117M
[INFO] ------------------------------------------------------------------------

application.properties

Place the application.properties file under the src/resources folder

#Oracle Connection settings
spring.datasource.url=jdbc:oracle:thin:@rsh2:40051:mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

#JPA properties
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

StundentRepository.java

package com.javainterviewpoint;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface StudentRepository extends CrudRepository<Student, Long> 
{
    public List<Student> findById(long id);

    //@Query("select s from Student s where s.age <= ?")
    public List<Student> findByAgeLessThanEqual (long age);
}

Spring Data REST will create an implementation of StudentRepository automatically during runtime.
@RepositoryRestResource annotation will direct Spring to create RESTful endpoints

App.java

package com.javainterviewpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages =
{ "com.javainterviewpoint" })
public class App implements CommandLineRunner
{

    @Autowired
    StudentRepository studentRepository;
    
    public static void main(String[] args)
    {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void run(String... args) throws Exception
    {
        // Getting all Students
        System.out.println("***** All Students *******");
        for(Student st : studentRepository.findAll())
        {
            System.out.println(st);
        }
        
        // Getting the student with id 2
        System.out.println("***** Student with ID 2 *******");
        for(Student st : studentRepository.findById(2))
        {
            System.out.println(st);
        }
        
        // Getting the student with id 2
        System.out.println("***** Student with Age less than 33 *******");
        for(Student st : studentRepository.findByAgeLessThanEqual(33))
        {
            System.out.println(st);
        }
    }
}
  • @SpringBootApplication annotation does the work of @EnableAutoConfiguration, @Configuration and @ComponentScan annotations together
  • CommandLineRunner interface has an unimplemented run() method, In our App class we have implemented the CommandLineRunner interface and have overridden the run() method. So when the SpringApplication.run() of the App class starts the spring boot application just before the application gets started, CommandLineRunner.run() will be executed.

Student.java

package com.javainterviewpoint;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student
{
    @Id
    @GeneratedValue
    @Column(name="ID")
    private long id;
    
    @Column(name="NAME")
    private String name;
    
    @Column(name="AGE")
    private long age;

    public Student()
    {
        super();
    }
    public Student(long id, String name, long age)
    {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public long getId()
    {
        return id;
    }
    public void setId(long id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public long getAge()
    {
        return age;
    }
    public void setAge(long age)
    {
        this.age = age;
    }
    
    @Override
    public String toString()
    {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

Our Student class is a simple POJO class consisting of the getters and setters for the Student class properties (id, name, age).

In the POJO class, we have used the below JPA Annotations.

  1. @Entity – This annotation will mark our Employee class as an Entity Bean.
  2. @Table – @Table annotation will map our class to the corresponding database table. You can also specify other attributes such as indexes, catalog, schema, uniqueConstraints. The @Table annotation is an optional annotation if this annotation is not provided then the class name will be used as the table name.
  3. @Id –  The @Id annotation marks the particular field as the primary key of the Entity.
  4. @GeneratedValue – This annotation is used to specify how the primary key should be generated. Here SEQUENCE Strategy will be used as this the default strategy for Oracle

Output

Run our application using the command “mvn spring-boot:run”, you will get the below output

 ***** All Students *******
2017-07-14 13:47:41.076 INFO 4424 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select student0_.id as id1_0_, student0_.age as age2_0_, student0_.name as name3_0_ from student student0_
Student [id=1, name=JIP1, age=11]
Student [id=2, name=JIP2, age=22]
Student [id=3, name=JIP3, age=33]
Student [id=4, name=JIP4, age=44]
***** Student with ID 2 *******
Hibernate: select student0_.id as id1_0_, student0_.age as age2_0_, student0_.name as name3_0_ from student student0_ where student0_.id=?
Student [id=2, name=JIP2, age=22]
***** Student with Age less than 33 *******
Hibernate: select student0_.id as id1_0_, student0_.age as age2_0_, student0_.name as name3_0_ from student student0_ where student0_.age<=?
Student [id=1, name=JIP1, age=11]
Student [id=2, name=JIP2, age=22]
Student [id=3, name=JIP3, age=33]

On the other hand, issue a GET request (http://localhost:8080/) and it will return a JSON response.Under the _links section you can see there will be two links

  • http://localhost:8080/students (Name of the class with ‘s’ added)
  • http://localhost:8080/profile (Reference of ourself)

Spring Boot CRUDRepository Example1

Now click on the http://localhost:8080/students link you will get all the students added.

Spring Boot CRUDRepository Example2

Filed Under: J2EE, Java, Spring Boot, Spring Data, Spring Tutorial Tagged With: Spring Boot CRUDRepository Example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·