Spring Data JPA using Hibernate and Java Configuration with Annotations

In this tutorial, I’ll show you how to use Spring Data JPA to integrate a relational database (PostgreSQL in my example) into a Spring Boot application.

Spring Data JPA using Hibernate and Java Configuration - Thomas Vitale

I’ll use these technologies and tools:

  • Spring Tool Suite (STS) 3.8.4.RELEASE
  • Java 8
  • Spring Boot 1.5.3.RELEASE
  • Maven 3.3.9
  • PostgreSQL 9.6.2

1. The Project Structure

The final folder structure of our project.

The folder structure of the Spring Data JPA project as seen in STS

2. Create a new Spring Boot project

If you’re using STS, you can create a starter project by either selecting File > New > Spring Starter Project from the main menu or right-clicking on the Package Explorer and choose New > Spring Starter Project.

STS command to create a new Spring Starter Project

Dialog window to set parameters for the Spring Data JPA project

The list of dependencies of the Spring Data JPA project

In case you’re using another IDE like Eclipse, Netbeans or IntelliJ IDEA, you can create a new Maven project and add to the pom.xml file the dependencies listed in the next paragraph.

3. Maven Dependencies

spring-boot-starter-data-jpa is the critical dependency of our project. Then we need the driver for whatever SQL database we have chosen, in this case postgresql.

<?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">
<description>Demo application for Spring Data JPA</description>
<relativePath/> <!-- lookup parent from repository -->
view raw pom.xml hosted with ❤ by GitHub

I’m using PostgreSQL, but this example works fine also with other relational databases. For instance, if you want to use MySQL, all you need to do is replace the postgresql dependency with the MySQL one.


4. Spring Configuration using Java Annotations and Hibernate

Spring lets you use either Java configuration or XML configuration or a mix of the two. I’ll use a pure Java configuration. There are a few implementations of JPA: in this example, I’ll use Hibernate. Its properties are stored in a dedicated file.

@EnableJpaRepositories(basePackages = "com.thomasvitale.repository")
public class JpaConfig {
private Environment env;
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
return em;
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
return dataSource;
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
return transactionManager;
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.setProperty("hibernate.current_session_context_class", env.getProperty("hibernate.current_session_context_class"));
return properties;
view raw JpaConfig.java hosted with ❤ by GitHub
view raw jpa.properties hosted with ❤ by GitHub

If you’re using MySQL, pay attention to replace line 36 of JpaConfig.java with this one: vendorAdapter.setDatabase(Database.MYSQL); and change the relative values in the jpa.properties file:


5. Person Model

For the Person entity, first of all, I create a new table (persons) in my PostgreSQL database (called app).

CREATE TABLE persons( 
   id SERIAL, 
   firstName VARCHAR(32), 
   lastName VARCHAR(32), 

Then I code the mapping object model. The @Table(name = "persons") annotation specifies in which table to save a Person object. The @GeneratedValue(strategy = GenerationType.IDENTITY) is quite general. In PostgreSQL, I have defined the id attribute as SERIAL. In MySQL, you probably want to use AUTO_INCREMENT. That’s just fine; it works with both of them.

@Table(name = "persons")
public class Person {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
public Person() {
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
public Integer getId() {
return id;
public void setId(Integer 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 toString() {
return firstName + " " + lastName;
view raw Person.java hosted with ❤ by GitHub

6. Person Repository

Our PersonRepository extends the JpaRepository interface, which provides us with a lot of operations out-of-the-box, including the standard CRUD operations. You can also add custom operations like findByFirstName and findByLastName without writing any implementation: Spring Data JPA creates them for you!

public interface PersonRepository extends JpaRepository<Person, Integer> {
public Person findByFirstName(String firstName);
public List<Person> findByLastName(String lastName);

7. Demo

Let’s try some CRUD operations to test our application.

public class Application implements CommandLineRunner {
PersonRepository personRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
public void run(String... arg0) throws Exception {
// Save three Person documents on PostgreSQL
personRepository.save(new Person("Sheldon", "Cooper"));
personRepository.save(new Person("Missy", "Cooper"));
personRepository.save(new Person("Leonard", "Hofstadter"));
// Get all the people
System.out.println(">>> All the people in the database:");
// Get all the people with a specific last name
System.out.println(">>> All people with last name = 'Cooper'");
// Update an individual person
Person person = personRepository.findByFirstName("Sheldon");
// Delete all
view raw Application.java hosted with ❤ by GitHub


Leave a Reply

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