DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Power BI Report by Pulling Data From SQL Tables
  • Leveraging FastAPI for Building Secure and High-Performance Banking APIs
  • Grow Your Skills With Low-Code Automation Tools
  • Introduction to Apache Camel

Trending

  • Power BI Report by Pulling Data From SQL Tables
  • Leveraging FastAPI for Building Secure and High-Performance Banking APIs
  • Grow Your Skills With Low-Code Automation Tools
  • Introduction to Apache Camel
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot and Spring Data JPA Integration

Spring Boot and Spring Data JPA Integration

This tutorial steps you through the process of creating a Spring Boot application connected to a PostgreSQL server

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Jun. 04, 16 · Tutorial
Like (7)
Save
Tweet
Share
35.89K Views

Join the DZone community and get the full member experience.

Join For Free

Nowadays, spring and JPA integration have become a piece of cake thanks to Spring Boot and spring Data.

I am going setup a postgresql server:

docker pull postgres
#run the container
docker run --name postgreslocal -e POSTGRES_PASSWORD=postgres -d postgres
#get the ip
docker inspect --format '{{ .NetworkSettings.IPAddress }}' postgreslocal
#get the port
docker inspect --format '{{ .NetworkSettings.Ports }}' postgreslocal

Create the employees Table:

create schema spring_data_jpa_example;

create table spring_data_jpa_example.employee(
id SERIAL PRIMARY KEY,
firstnameTEXTNOT NULL,
lastnameTEXTNOT NULL,
 emailTEXT not null,
 age INT NOT NULL,
 salary real,
unique(email)
);

insert into spring_data_jpa_example.employee (firstname,lastname,email,age,salary) 
values ('Emmanouil','Gkatziouras','gkatzioura@gmail.com',18,3000.23);

Let’s begin with our gradle file:

group 'com.gkatzioura'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

buildscript {
 repositories {
 mavenCentral()
 }
 dependencies {
 classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
 }
}

apply plugin: 'idea'
apply plugin: 'spring-boot'

repositories {
 mavenCentral()
}

dependencies {
 compile("org.springframework.boot:spring-boot-starter-web") {
 exclude module: "spring-boot-starter-tomcat"
 }
 compile("org.postgresql:postgresql:9.4-1206-jdbc42")
 compile("org.springframework.boot:spring-boot-starter-jetty")
 compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.3.RELEASE")
 compile("com.mchange:c3p0:0.9.5.2")
 testCompile("junit:junit:4.11");
}

As you see, we added the c3p0 connection pool, the spring-boot-starter-data-jpa for hibernate and the postgres driver. That’s all we need.

The Application Class

package com.gkatzioura.springdata.jpa;

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

/**
 * Created by gkatzioura on 6/2/16.
 */
@SpringBootApplication
public class Application {


 public static void main(String[] args) {

 SpringApplication springApplication = new SpringApplication();
 ApplicationContext ctx = springApplication.run(Application.class, args);
 }
}

The DataSource Configuration


package com.gkatzioura.springdata.jpa.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Configuration
public class DataSourceConfig {

 @Bean
 public DataSource createDataSource() throws Exception {

 ComboPooledDataSource ds = new ComboPooledDataSource();
 ds.setJdbcUrl("jdbc:postgresql://172.17.0.3:5432/postgres?user=postgres&password=postgres");
 ds.setDriverClass("org.postgresql.Driver");

 return ds;
 }

}

The Employee entity


package com.gkatzioura.springdata.jpa.persistence.entity;

import javax.persistence.*;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Entity
@Table(name = "employee", schema="spring_data_jpa_example")
public class Employee {

 @Id
 @Column(name = "id")
 @GeneratedValue(strategy = GenerationType.SEQUENCE)
 private Long id;

 @Column(name = "firstname")
 private String firstName;

 @Column(name = "lastname")
 private String lastname;

 @Column(name = "email")
 private String email;

 @Column(name = "age")
 private Integer age;

 @Column(name = "salary")
 private Integer salary;

 public Long getId() {
 return id;
 }

 public void setId(Long id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastname() {
 return lastname;
 }

 public void setLastname(String lastname) {
 this.lastname = lastname;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public Integer getAge() {
 return age;
 }

 public void setAge(Integer age) {
 this.age = age;
 }

 public Integer getSalary() {
 return salary;
 }

 public void setSalary(Integer salary) {
 this.salary = salary;
 }
}

The employee repository

package com.gkatzioura.springdata.jpa.persistence.repository;

import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}

And a controller that will fetch all the data

package com.gkatzioura.springdata.jpa.controller;

import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import com.gkatzioura.springdata.jpa.persistence.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by gkatzioura on 6/2/16.
 */
@RestController
public class TestController {

 @Autowired
 private EmployeeRepository employeeRepository;

 @RequestMapping("/employee")
 public List<Employee> getTest() {

 return employeeRepository.findAll();
 }
}

Pretty convenient considering the dependencies and the XML configuration overhead of the past.

You can find the source code on GitHub.

 
Spring Framework Spring Boot Spring Data Data (computing)

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Power BI Report by Pulling Data From SQL Tables
  • Leveraging FastAPI for Building Secure and High-Performance Banking APIs
  • Grow Your Skills With Low-Code Automation Tools
  • Introduction to Apache Camel

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: