In this tutorials, we will see how to integrate Spring Boot with data JPA as Spring Boot JPA Example.
Spring Boot JPA Integration :
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
Spring Boot JPA Project Structure:
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:)