Saturday , April 29 2017
Home / Spring Boot / Spring Boot JPA Integration Example

Spring Boot JPA Integration Example

In this tutorials, we are going to show you how to integrate Spring Boot with data JPA as  Spring Boot JPA Example. This includes how to integrate the simple spring boot application with Spring Data JPA.

Spring Boot JPA Integration

Spring Boot JPA Integration :

Here we are going to use the below technologies:

  • Java 8
  • Spring Boot 1.5.1.RELEASE
  • Spring Data JPA 1.11.0.RELEASE
  • Mysql

Spring Boot JPA Project Structure :

A typical maven project directory structure,

Spring Boot JPA

Required Dependencies :

Here, the most important thing is to defining the dependencies for Spring Boot JPA related.

Unlike the spring mvc with hibernate integration, we don’t need here a separate dependencies for spring boot and spring data jpa.

Hence we can define a single spring artifactid as spring-boot-starter-data-jpa, it will grasp all the dependencies for Spring boot and data jpa.

Since we are working with Mysql data base, we should declare the dependency for mysql connector too.

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/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>

This example is to connecting with Spring Boot JPA application with Mysql database, I am going to access the below person table.

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)
)

Create a properties file with data base connection properties :

application.properties


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


Here the actual magic will come in to picture! Spring boot provides a bunch of application level properties to manage our application configurations.

By using this properties, we can eliminate the boiler plated code for creating the database configurations like datasources and transactions. Spring boot will take the responsibility to create all these kinds of stuff for us. Hence there is no boiler plate data source configurations here.

Creating a repository interface.

PersonRepository.java

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>{
}

Here @Repository is a spring stereo type annotation , used to tell the spring context, it is a persistent layered class.

CrudRepository is an interface given by the spring data, which gives us the basic crud operations on a repository for a specific type. Here in our example the specific type is Person class.

In any typical hibernate using applications like spring with hibernate, we need to write all the CRUD operations of our own. Where as in Spring data JPA, CrudRepository provides sophisticated  CRUD operations for entity class.

Creating Entity class :

Person.java

It is a typical JPA 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 :

PersonService.java

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<Person> getAllPersons() {
        return (List<Person>) 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 stereo type annotation , used to tell the spring context, it is a service layered class.

Creating DTO class :

PersonDTO.java


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 :

Application.java

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 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.

Lets 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 every thing goes well you will see the output like this:

Spring Boot JPA Output

On the above output you can see the SQL command for insert person data.

Happy Learning:)

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave a Reply

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