Setup Spring Boot Project and View In-Memory Database

0
484
Springboot

What is JPA?

JPA (Java Persistence API) is an interface that describes the management of relational data in applications using Java platform. It defines API for the below-

  •       Entities
  •       Attributes
  •       Map relationship between entities
  •       Managing the entities

What is Hibernate?

Hibernate is an Object-Relational Mapping tool that maps object oriented domain model to relational database. It implements the Java Persistence API’s and other advance features. 

Let’s start getting our hands dirty:

How to create Spring Boot JPA project using Spring Initializer?

Create a new project via Spring Initializer
  •  Now import the zipped project into Intellij. You can use any IDE of your choice.
Import into Intellij

How to create Entity and Service to Manage?

Step 1: Create Employee.java entity as seen below:

package com.learn.spring.jpa.jpademo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Employee {

@Id
@GeneratedValue
private long id;
private String name;
private String department;

protected Employee() {
}

public long getId() {
return id;
}

public Employee(String name, String department) {
this.name = name;
this.department = department;
}

public String getName() {
return name;
}

public String getDepartment() {
return department;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", department='" + department + '\'' +
'}';
}
}

Step 2:  Create EmployeeDAOService.java class which is required for persisting the entity Employee.

package com.learn.spring.jpa.jpademo.service;

import com.learn.spring.jpa.jpademo.entity.Employee;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;


@Repository
@Transactional
public class EmployeeDAOService {

    @PersistenceContext
    private EntityManager entityManager;

    public long insert(Employee employee){
        entityManager.persist(employee);
        return employee.getId();
    }
}

Step 3: Save Employee Entity – 

Create EmployeeDAOServiceCommandLineRunner.java class to insert the data into database as seen below:

package com.learn.spring.jpa.jpademo;

import com.learn.spring.jpa.jpademo.entity.Employee;
import com.learn.spring.jpa.jpademo.service.EmployeeDAOService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class EmployeeDAOServiceCommandLineRunner implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(EmployeeDAOServiceCommandLineRunner.class);

    @Autowired
    private EmployeeDAOService employeeDAOService;

    @Override
    public void run(String... args) throws Exception {
        Employee emp = new Employee("James", "Engineer");
        long insertId = employeeDAOService.insert(emp);
        logger.info("Emploee inserted : " + emp);
    }
}

Step 4: Run JpaDemoApplication as Java application, you can see the below logs in the console:

2018-10-23 15:38:09.960  INFO 12892 --- [           main] c.l.s.jpa.jpademo.JpademoApplication     : Started JpademoApplication in 8.378 seconds (JVM running for 9.072)
2018-10-23 15:38:10.090  INFO 12892 --- [           main] .j.j.EmployeeDAOServiceCommandLineRunner : Emploee inserted : Employee{id=1, name='James', department='Engineer'}

To see SQL Queries in Console Logs:

Step 5:  Terminate the application and re-run the application. Now lets add two properties in application.properties

spring.jpa.show-sql = true   // Enables all sql querries being executed 
spring.h2.console.enabled = true // To see the h2 database console

The console messages clearly shows that the table & sequence is dropped if exist, and are re-created again as seen below:

Hibernate: drop table employee if exists
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1Hibernate: create table employee (id bigint not null, department varchar(255), name varchar(255), primary key (id))
Hibernate: call next value for hibernate_sequence
Hibernate: insert into employee (department, name, id) values (?, ?, ?)
2018-10-23 15:45:50.061  INFO 3440 --- [           main] .j.j.EmployeeDAOServiceCommandLineRunner : Emploee inserted : Employee{id=1, name='James', department='Engineer'}

To view In-Memory Database (h2)

Step 6: Login to h2 database console – http://localhost:8080/h2-console/ and enter the JDBC url as seen below:

JDBC URL : jdbc:h2:mem:testdb and click Connect

H2 Console

Step 7: You would see h2 database and can see the data created as seen below:

h2 Console

SUMMARY:

  • Creating a Spring Boot JPA project using spring initializer.
  • Creating Entity and a Service to manage the entity.
  • To save entity with commandLineRunner.
  • Enabled sql queries and debug logs by adding property in application.properties.
  • Using in-memory H2 database for unit tests without a dedicated database.
  • Defining Repository interface extending JpaRepository for our entities.
  • You can find code of the same project which we built in this article on github repository SpringBootJPADemo.