Monday 19 August 2019

Spring Data JPA: saveAll: Save all the entities


CrudRepository interface provides 'saveAll' method, it is used to save all the entities to database.

<S extends T> Iterable<S> saveAll(Iterable<S> entities);
This method return all the saved entities.

Example
List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);
Iterable<Employee> persistedEmployees = employeeRepository.saveAll(emps);

Find the below working application.

Step 1: Create model class Employee.

Employee.java
package com.sample.app.model;

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 = "employee")
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "employee_id")
 private int id;
 
 @Column(name = "first_name")
 private String firstName;
 
 @Column(name = "last_name")
 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 2: Create EmployeeRepository interface like below.


EmployeeRepository
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 3: Create ‘application.properties’ file under src/main/resources.

application.properties
logging.level.root=WARN
logging.level.org.hibernate=ERROR

## 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
# Creates the schema, destroying previous data.
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

Step 4: Define App.java class like below.

App.java
package com.sample.app;

import java.util.Arrays;
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.repository.EmployeeRepository;

@SpringBootApplication
public class App {

    private static void printEmployee(Employee emp) {
        System.out.println("------------------------------");
        System.out.println("Id : " + emp.getId());
        System.out.println("firstName : " + emp.getFirstName());
        System.out.println("lastName : " + emp.getLastName());
        System.out.println("------------------------------");
    }

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

    @Bean
    public CommandLineRunner demo(EmployeeRepository employeeRepository) {
        return (args) -> {
            Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").build();
            Employee emp2 = Employee.builder().firstName("Rahim").lastName("Khan").build();
            Employee emp3 = Employee.builder().firstName("Robert").lastName("Chelli").build();
            Employee emp4 = Employee.builder().firstName("Sailaja").lastName("Navakotla").build();
            Employee emp5 = Employee.builder().firstName("Siva").lastName("Ponnam").build();

            List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

            Iterable<Employee> persistedEmployees = employeeRepository.saveAll(emps);

            for (Employee emp : persistedEmployees) {
                printEmployee(emp);
            }

        };
    }

}


Total project structure looks like below.


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

Hibernate: 
    
    drop table employee if exists
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table employee (
       employee_id integer not null,
        first_name varchar(255),
        last_name varchar(255),
        primary key (employee_id)
    )
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, employee_id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, employee_id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, employee_id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, employee_id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        employee
        (first_name, last_name, employee_id) 
    values
        (?, ?, ?)
------------------------------
Id : 1
firstName : Ram
lastName : Gurram
------------------------------
------------------------------
Id : 2
firstName : Rahim
lastName : Khan
------------------------------
------------------------------
Id : 3
firstName : Robert
lastName : Chelli
------------------------------
------------------------------
Id : 4
firstName : Sailaja
lastName : Navakotla
------------------------------
------------------------------
Id : 5
firstName : Siva
lastName : Ponnam
------------------------------

You can download complete working application from this link.

Previous                                                    Next                                                    Home

2 comments:

  1. How about saving 100s of thousands of entities using saveAll? Let's say, I have a feature which allows users to import 100000 rows of CSV data into the application, process them and persist them.

    ReplyDelete
  2. like whatis you want to get data from thymleaf page then what?

    ReplyDelete