Spring Boot JPA Integration | Spring Data JPA Boot Example | Online Tutorialspoint

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 tutorials, we will see how to integrate Spring Boot with data JPA as  Spring Boot JPA Example.
Here we are going to use the below technologies:
Spring Boot 1.5.1.RELEASE
Spring Data JPA 1.11.0.RELEASE
Java 8
Mysql
STS
A typical maven project directory structure,
 
Here, the most important point is to define the dependencies for Spring Boot JPA related.
Unlike the spring MVC with hibernate integration, we do not need to define separate dependencies for both spring boot and spring data jpa.
A single spring-boot-starter-data-jpa brings all the dependencies for Spring boot and data jpa.
Since we are working with Mysql database, we should declare the dependency for MySQL connector too.
Recommended: Spring Boot with JPA multiple Data Sources Example
<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>org.springframework.samples</groupId>
  <artifactId>Spring_JPA_Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>         <!-- Generic properties -->
    <java.version>1.8</java.version>
  </properties>
  <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-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <repositories>
    <repository>
      <id>spring-releases</id>
      <name>Spring Releases</name>
      <url>https://repo.spring.io/libs-release</url>
    </repository>
    <repository>
      <id>org.jboss.repository.releases</id>
      <name>JBoss Maven Release Repository</name>
      <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <id>spring-releases</id>
      <name>Spring Releases</name>
      <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
  </pluginRepositories>
</project>
Create person table :
CREATE TABLE person (
id INT(11) NOT NULL AUTO_INCREMENT,
pcity VARCHAR(255) NULL DEFAULT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
)

Creating a property file, having all database configuration details:
spring.datasource.driver-class-name:com.mysql.jdbc.Driver
spring.datasource.url:jdbc:mysql://localhost:3306/onlinetutorialspoint
spring.datasource.username:root
spring.datasource.password:123456

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

The above-mentioned properties are provided by spring-boot, typically called as application-level properties to manage our application configurations.
By using these properties, we can eliminate the boilerplate code to configure the data sources and transactions.
Creating a repository interface.
package com.onlinetutorialspoint.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.onlinetutorialspoint.entity.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person, Long>{
}

CrudRepository is an interface given by the spring data, which gives us the basic crud operations on a repository for a specific type.
In any typical hibernate using applications like spring with hibernate integration, we need to write all the CRUD operations of our own. Whereas in Spring Data JPA, CrudRepository provides in-built CRUD operations for the entity class.
Creating Entity class :
package com.onlinetutorialspoint.entity;

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

@Entity
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @Column(name="pcity")
    private String city;

    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }

    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 String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Person [pid=" + id + ", pName=" + name + ", pCity=" + city
                + "]";
    }

}


Creating a service class :
package com.onlinetutorialspoint.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onlinetutorialspoint.dto.PersonDTO;
import com.onlinetutorialspoint.entity.Person;
import com.onlinetutorialspoint.repository.PersonRepository;

@Service
@Transactional
public class PersonService {
    @Autowired
    PersonRepository personRepo;

    public void savePersonDetails(PersonDTO personDto) {
        try {
            Person person = new Person();
            person.setCity(personDto.getpCity());
            person.setName(personDto.getpName());
            person.setId(personDto.getPid());
            personRepo.save(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List getAllPersons() {
        return (List) personRepo.findAll();
    }

    public Person getPerson(long id) {
        return personRepo.findOne(id);
    }

    public Person savePerson(Person person) {
        return personRepo.save(person);
    }
}

Here @Service is a spring stereotype annotation, used to tell the spring context, it is a service layered class.
Creating DTO class :
package com.onlinetutorialspoint.dto;

public class PersonDTO {
    private Long pid;
    private String pName;
    private String pCity;
    public Long getPid() {
        return pid;
    }
    public void setPid(Long pid) {
        this.pid = pid;
    }
    public String getpName() {
        return pName;
    }
    public void setpName(String pName) {
        this.pName = pName;
    }    
    public String getpCity() {
        return pCity;
    }
    public void setpCity(String pCity) {
        this.pCity = pCity;
    }
}

Spring Boot Application class :
package com.onlinetutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.web.config.EnableSpringDataWebSupport;

import com.onlinetutorialspoint.entity.Person;
import com.onlinetutorialspoint.repository.PersonRepository;
import com.onlinetutorialspoint.service.PersonService;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
    @Autowired
    PersonService personService;
    @Bean
    public CommandLineRunner run(PersonRepository repository) {
        return (args) -> {
            Person person = new Person();
            person.setName("Chandra Shekhar Goka");
            person.setCity("Hyderabad");
            Person p = savePersonDetails(person);
            
            System.out.println("Person Id : "+p.getId() +" Person Name : "+p.getName());
        };
    }
    
    public Person savePersonDetails(Person p){
        return personService.savePerson(p);
    }
    
    public Person getPerson(Person person){
        return personService.getPerson(person.getId());
    }
}


@SpringBootApplication annotation tells to Spring Boot, this is a starting point of our Spring Boot Application.
CommandLineRunner is an interface provided by the spring boot. It is used to indicate that a bean should run when it is contained within a spring application.
In the run method, I have created a Person class and call a savePerson method on PersonService class in Java 8 lambda expression to save the person details.
Let’s run the Application.java to save the person details. You can run this application as simple as Java standalone application by running the main class.
If everything goes well you will see the output like this:
On the above output, you can see the SQL command for insert person data.
Happy Learning:)


Spring Boot with JPA Integration

File size: 18 KB
Downloads: 1339


Spring Boot Hibernate Integration Example
Spring Boot Security MySQL Database Integration Example
Spring Boot Multiple Data Sources Example
Spring Boot PDF iText integration with String Template
Spring Boot PostgreSQL DB CRUD Example
Simple Spring Boot Example
How to set Spring Boot SetTimeZone
Spring Boot – How to load initial data on startup
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot H2 Database + JDBC Template Example
Spring Boot DataRest Example RepositoryRestResource
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot MongoDB + Spring Data Example
External Apache ActiveMQ Spring Boot Example

Spring Boot Hibernate Integration Example
Spring Boot Security MySQL Database Integration Example
Spring Boot Multiple Data Sources Example
Spring Boot PDF iText integration with String Template
Spring Boot PostgreSQL DB CRUD Example
Simple Spring Boot Example
How to set Spring Boot SetTimeZone
Spring Boot – How to load initial data on startup
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot H2 Database + JDBC Template Example
Spring Boot DataRest Example RepositoryRestResource
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot MongoDB + Spring Data Example
External Apache ActiveMQ Spring Boot Example






Suhas
September 28, 2017 at 2:09 pm - Reply 

where is the implementation for findAll(). Am not able to Autowire  the repository in service. am getting UnsatisfiedDependencyException. but this ecxeption vanishes once i give a dummy implementation.









Suhas
September 28, 2017 at 2:10 pm - Reply 

If implementation is needed then pls do tell me how to implement.









chandrashekhar
October 20, 2017 at 11:16 am - Reply 

Hi Suhas,
Spring JPA gives us default implementations, we do not need to implement on our own.









chandrashekhar
October 20, 2017 at 11:19 am - Reply 

Typically UnsatisfiedDependencyException comes when you miss to define the annotations : (@Repository,@Service and etc..) on top of the classes. Please make sure of this.












Suhas
September 28, 2017 at 2:09 pm - Reply 

where is the implementation for findAll(). Am not able to Autowire  the repository in service. am getting UnsatisfiedDependencyException. but this ecxeption vanishes once i give a dummy implementation.









Suhas
September 28, 2017 at 2:10 pm - Reply 

If implementation is needed then pls do tell me how to implement.









chandrashekhar
October 20, 2017 at 11:16 am - Reply 

Hi Suhas,
Spring JPA gives us default implementations, we do not need to implement on our own.









chandrashekhar
October 20, 2017 at 11:19 am - Reply 

Typically UnsatisfiedDependencyException comes when you miss to define the annotations : (@Repository,@Service and etc..) on top of the classes. Please make sure of this.






where is the implementation for findAll(). Am not able to Autowire  the repository in service. am getting UnsatisfiedDependencyException. but this ecxeption vanishes once i give a dummy implementation.





Suhas
September 28, 2017 at 2:10 pm - Reply 

If implementation is needed then pls do tell me how to implement.




If implementation is needed then pls do tell me how to implement.





chandrashekhar
October 20, 2017 at 11:16 am - Reply 

Hi Suhas,
Spring JPA gives us default implementations, we do not need to implement on our own.




Hi Suhas,
Spring JPA gives us default implementations, we do not need to implement on our own.





chandrashekhar
October 20, 2017 at 11:19 am - Reply 

Typically UnsatisfiedDependencyException comes when you miss to define the annotations : (@Repository,@Service and etc..) on top of the classes. Please make sure of this.




Typically UnsatisfiedDependencyException comes when you miss to define the annotations : (@Repository,@Service and etc..) on top of the classes. Please make sure of this.
 


Δ
 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