Saturday 17 August 2019

Spring Data JPA: Hello World Application


I am going to use spring boot throughout this tutorial.

Step 1: Create new maven project ‘springJPA’.

File -> New -> Other.

Search for Maven.


Select ‘Maven Project’ and click Next button.

Select the check box ‘Create a simple project (skip archetype selection)’. Click on Next button.

Give the Group Id, Artifact Id as ‘springJPA, version as 1 and click on Finish button.

It creates project structure looks like below.

Step 2: Update pom.xml with spring boot jpa dependencies.
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>springJPA</groupId>
 <artifactId>springJPA</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>



 <dependencies>


  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
  </dependency>


 </dependencies>

</project>

Step 3: Create ‘application.properties’ file under ‘src/main/resources’ and add database, jpa specific details there.

application.properties
# Setting log level to DEBUG
logging.level.org.springframework.web=DEBUG

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
spring.jpa.hibernate.ddl-auto=create

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3


I am using H2 database for this tutorial series.  ‘myOrg’ is the database name.

Step 4: Create a package com.sample.app.model, and define Employee class like below.
Employee.java
package com.sample.app.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int 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 static EmployeeBuilder builder() {
  return new EmployeeBuilder();
 }

 public static class EmployeeBuilder {
  private Employee emp;

  public EmployeeBuilder() {
   emp = new Employee();
  }

  public EmployeeBuilder firstName(String firstName) {
   emp.setFirstName(firstName);
   return this;
  }

  public EmployeeBuilder lastName(String lastName) {
   emp.setLastName(lastName);
   return this;
  }

  public Employee build() {
   return emp;
  }
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


Step 5: Create a package ‘com.sample.app.repository and define EmployeeRepository interface like below.
EmployeeRepository.java    
package com.sample.app.repository;

import org.springframework.data.repository.CrudRepository;

import com.sample.app.model.Employee;  

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {

 
}


Step 6: Create a package ‘com.sample.app.service’ and define EmployeeService class like below.

EmployeeService.java    
package com.sample.app.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sample.app.model.Employee;
import com.sample.app.repository.EmployeeRepository;

@Service
public class EmployeeService {

 @Autowired
 private EmployeeRepository employeeRepository;

 public List<Employee> getAllEmployees() {
  List<Employee> emps = new ArrayList<>();
  employeeRepository.findAll().forEach(emps::add);
  return emps;
 }

 public Optional<Employee> getEmployee(int id) {
  return employeeRepository.findById(id);
 }

 public Employee createEmployee(Employee emp) {
  return employeeRepository.save(emp);
 }

 public Employee deleteEmployee(int id) {
  Optional<Employee> emp = employeeRepository.findById(id);
  
  if(!emp.isPresent()) {
   return null;
  }
  
  Employee returnedEmp = emp.get();
  employeeRepository.deleteById(id);
  return returnedEmp;
 }

 public Employee updateEmployee(Employee emp) {
  Optional<Employee> persistedEmp = employeeRepository.findById(emp.getId());

  if (!persistedEmp.isPresent()) {
   return null;
  }

  Employee employeeFromDB = persistedEmp.get();
  employeeFromDB.setFirstName(emp.getFirstName());
  employeeFromDB.setLastName(emp.getLastName());

  return employeeRepository.save(employeeFromDB);

 }
}


Step 7: Define App.java in ‘com.sample.app’ package.
App.java    
package com.sample.app;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

@SpringBootApplication
public class App {
 public static void main(String args[]) {
  SpringApplication.run(App.class, args);
 }

 @Bean
 public CommandLineRunner demo(EmployeeService employeeService) {
  return (args) -> {
   Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").build();
   Employee emp2 = Employee.builder().firstName("Ram").lastName("Gurram").build();
   Employee emp3 = Employee.builder().firstName("Ram").lastName("Gurram").build();
   Employee emp4 = Employee.builder().firstName("Ram").lastName("Gurram").build();

   employeeService.createEmployee(emp1);
   employeeService.createEmployee(emp2);
   employeeService.createEmployee(emp3);
   employeeService.createEmployee(emp4);

   List<Employee> emps = employeeService.getAllEmployees();

   System.out.println("-------------------------");
   System.out.println("Printing Employees");
   System.out.println("-------------------------");
   for (Employee emp : emps) {
    System.out.println(emp);
   }

   System.out.println("Deleting employees");

   employeeService.deleteEmployee(emp1.getId());
   employeeService.deleteEmployee(emp2.getId());
   employeeService.deleteEmployee(emp3.getId());
   employeeService.deleteEmployee(emp4.getId());

   emps = employeeService.getAllEmployees();

   System.out.println("\n\n-------------------------");
   System.out.println("Printing Employees");
   System.out.println("-------------------------");
   for (Employee emp : emps) {
    System.out.println(emp);
   }

  };
 }

}


Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-08 10:17:24.002  INFO 3813 --- [           main] com.sample.app.App                       : Starting App on C02X902SJGH5 with PID 3813 (/Users/krishna/Documents/EclipseWorkSpaces/Learnings/springJPA/target/classes started by krishna in /Users/krishna/Documents/EclipseWorkSpaces/Learnings/springJPA)
2019-07-08 10:17:24.004  INFO 3813 --- [           main] com.sample.app.App                       : No active profile set, falling back to default profiles: default
2019-07-08 10:17:24.366  INFO 3813 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-08 10:17:24.416  INFO 3813 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 repository interfaces.
2019-07-08 10:17:24.783  INFO 3813 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-07-08 10:17:24.997  INFO 3813 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-07-08 10:17:25.041  INFO 3813 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-07-08 10:17:25.092  INFO 3813 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-07-08 10:17:25.093  INFO 3813 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-08 10:17:25.226  INFO 3813 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-08 10:17:25.350  INFO 3813 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: 
    
    create table employee (
       id integer not null,
        first_name varchar(255),
        last_name varchar(255),
        primary key (id)
    )
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
2019-07-08 10:17:25.920  INFO 3813 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-08 10:17:26.241  INFO 3813 --- [           main] com.sample.app.App                       : Started App in 2.475 seconds (JVM running for 2.766)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, id) 
    values
        (?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, id) 
    values
        (?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, id) 
    values
        (?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, id) 
    values
        (?, ?, ?)
2019-07-08 10:17:26.317  INFO 3813 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        employee0_.id as id1_0_,
        employee0_.first_name as first_na2_0_,
        employee0_.last_name as last_nam3_0_ 
    from
        employee employee0_
-------------------------
Printing Employees
-------------------------
Employee [id=1, firstName=Ram, lastName=Gurram]
Employee [id=2, firstName=Ram, lastName=Gurram]
Employee [id=3, firstName=Ram, lastName=Gurram]
Employee [id=4, firstName=Ram, lastName=Gurram]
Deleting employees
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    delete 
    from
        employee 
    where
        id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    delete 
    from
        employee 
    where
        id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    delete 
    from
        employee 
    where
        id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    select
        employee0_.id as id1_0_0_,
        employee0_.first_name as first_na2_0_0_,
        employee0_.last_name as last_nam3_0_0_ 
    from
        employee employee0_ 
    where
        employee0_.id=?
Hibernate: 
    delete 
    from
        employee 
    where
        id=?
Hibernate: 
    select
        employee0_.id as id1_0_,
        employee0_.first_name as first_na2_0_,
        employee0_.last_name as last_nam3_0_ 
    from
        employee employee0_


-------------------------
Printing Employees
-------------------------
2019-07-08 10:17:26.434  INFO 3813 --- [       Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-07-08 10:17:26.436  INFO 3813 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-07-08 10:17:26.438  INFO 3813 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment