Spring Data JPA deleteAll() Vs deleteAllInBatch()

In this tutorial, we will see about Spring Data JPA deleteAll() Vs deleteAllInBatch() Example using Spring Boot and Oracle.

The deleteAll() method is defined in CrudRepository has two overloaded versions.

First one – void deleteAll(Iterable<? extends T> entities)

Using the above method we can delete all entities which we pass as request data. The deleteAll() internally use delete() method only.

	public void deleteAll(Iterable<? extends T> entities) {
		for (T entity : entities) {
			delete(entity);
		}
	}

Second one – void deleteAll()

The above one will delete all records that belong to that repository. The deleteAll() internally uses findAll() and delete() method as below.

	public void deleteAll() {

		for (T element : findAll()) {
			delete(element);
		}
	}

The query generated in case of deleteAll(). Suppose we are deleting twelve entities.

Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?
Hibernate: delete from student where id=?

The deleteAllInBatch() method is defined in the JpaRepository interface as below.

void deleteAllInBatch()


Using deleteAllInBatch() method we can delete all entities from database. No need to pass entities as parameters.For example, let’s say we have an entity Student.java and also we have a corresponding repository class called StudentRepository.java something like below.

package com.netsurfingzone.repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

If we want to delete all student records we need to do studentRepository.deleteAllInBatch().  See the below sample code.

	@Transactional
	public void deleteAllInBatch() {
		studentRepository.deleteAllInBatch();
	}

Note – Internally deleteAllInBatch()   uses createQuery() method as below.

	public void deleteAllInBatch() {
		em.createQuery(getDeleteAllQueryString()).executeUpdate();
	}

In case of deleteAllInBatch() the query will generate as below.

Hibernate: delete from student

Both deleteAll() and deleteAllInBatch() use to delete all entities. The deleteAll() internally uses CrudRepository delete() method which further uses EntityManger remove() method which perform some other stuff. But in case of deleteAllInBatch(), EntityManger createQuery() method will preapare the query and it directly calls executeUpdate() method.

Let’s see an example of Spring Data JPA deleteAll() vs deleteAllInBatch() Method.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springdatadeleteallvsdeleteallinbatch, ArtifactId – springdatadeleteallvsdeleteallinbatch and name – springdatadeleteallvsdeleteallinbatch) and click on finish. Keep packaging as the jar.

Modify 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>springdatadeleteallvsdeleteallinbatch</groupId>
	<artifactId>springdatadeleteallvsdeleteallinbatch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springdatadeleteallvsdeleteallinbatch</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

The directory structure for Spring Data JPA CrudRepository count() Example using Spring Boot and Oracle.

Directory structure –


Spring Data JPA CrudRepository count() Example

Spring Data JPA CrudRepository count() Example

Student.java

package com.netsurfingzone.entity;

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

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

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

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

StudentController.java

package com.netsurfingzone.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/saveall", method = RequestMethod.POST)
	@ResponseBody
	public List<Student> saveAllStudents(@RequestBody List<Student> studentList) {
		List<Student> studentResponse = (List<Student>) studentService.saveAllStudent(studentList);
		return studentResponse;
	}

	@RequestMapping(value = "/deleteall", method = RequestMethod.DELETE)
	@ResponseBody
	public String deleteAll() {
		studentService.deleteAll();
		return "All Students deleted successfully using deleteAll()";
	}

	@RequestMapping(value = "/deleteallinbatch", method = RequestMethod.DELETE)
	@ResponseBody
	public String deleteAllInBatch() {
		studentService.deleteAllInBatch();
		return "All Students deleted successfully using deleteAllInBatch()";
	}

}

StudentRepository.java – interface

package com.netsurfingzone.repository;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.netsurfingzone.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

StudentService.java – interface

package com.netsurfingzone.service;

import java.util.List;

import org.springframework.stereotype.Component;

import com.netsurfingzone.entity.Student;

@Component
public interface StudentService {
	public List<Student> saveAllStudent(List<Student> studentList);

	public void deleteAll();

	public void deleteAllInBatch();

}

Spring Data JPA CrudRepository count() Example

StudentServiceImpl.java


package com.netsurfingzone.impl;

import java.util.List;

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

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.repository.StudentRepository;
import com.netsurfingzone.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public List<Student> saveAllStudent(List<Student> studentList) {
		List<Student> response = (List<Student>) studentRepository.saveAll(studentList);
		return response;
	}

	@Transactional
	public void deleteAll() {
		studentRepository.deleteAll();
	}

	@Transactional
	public void deleteAllInBatch() {
		studentRepository.deleteAllInBatch();
	}

}

SpringMain.java

package com.netsurfingzone.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.netsurfingzone.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

JpaConfig.java

package com.netsurfingzone.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.netsurfingzone.repository")
public class JpaConfig {

}

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

Perform save operation first using below REST API.

http://localhost:9091/student/saveall

Request Data –

[
    {
        "name": "Hiteshdo",
        "rollNumber": "0126CS01",
        "university":"rgtu"
    },
    {
        "name": "Johnhjhjhjhj",
        "rollNumber": "0126CS02",
        "university":"rgtu"
    },
    {
        "name": "Mohankkkkkkkkkkkkkk",
        "rollNumber": "0126CS03",
        "university":"rgtu"
    },
    {
        "name": "Nagesh",
        "rollNumber": "0126CS04",
        "university":"rgtu"
    },
    {
        "name": "s",
        "rollNumber": "0126CS05",
        "university":"rgtu"
    },
    {
        "name": "Ranakum",
        "rollNumber": "0126CS06",
        "university":"rgtu"
    },
    {
        "name": "Roc",
        "rollNumber": "0126CS07",
        "university":"rgtu"
    },
    {
        "name": "Simpy",
        "rollNumber": "0126CS08",
        "university":"rgtu"
    },
    {
        "name": "Tiwari",
        "rollNumber": "0126CS09",
        "university":"rgtu"
    },    {
        "name": "Appu",
        "rollNumber": "0126CS10",
        "university":"rgtu"
    },
    {
        "name": "Babloo",
        "rollNumber": "0126CS11",
        "university":"rgtu"
    },
    {
        "name": "Ga",
        "rollNumber": "0126CS12",
        "university":"rgtu"
    }
]

Response data –

[
    {
        "id": 1,
        "name": "Hiteshdo",
        "rollNumber": "0126CS01",
        "university": "rgtu"
    },
    {
        "id": 2,
        "name": "Johnhjhjhjhj",
        "rollNumber": "0126CS02",
        "university": "rgtu"
    },
    {
        "id": 3,
        "name": "Mohankkkkkkkkkkkkkk",
        "rollNumber": "0126CS03",
        "university": "rgtu"
    },
    {
        "id": 4,
        "name": "Nagesh",
        "rollNumber": "0126CS04",
        "university": "rgtu"
    },
    {
        "id": 5,
        "name": "s",
        "rollNumber": "0126CS05",
        "university": "rgtu"
    },
    {
        "id": 6,
        "name": "Ranakum",
        "rollNumber": "0126CS06",
        "university": "rgtu"
    },
    {
        "id": 7,
        "name": "Roc",
        "rollNumber": "0126CS07",
        "university": "rgtu"
    },
    {
        "id": 8,
        "name": "Simpy",
        "rollNumber": "0126CS08",
        "university": "rgtu"
    },
    {
        "id": 9,
        "name": "Tiwari",
        "rollNumber": "0126CS09",
        "university": "rgtu"
    },
    {
        "id": 10,
        "name": "Appu",
        "rollNumber": "0126CS10",
        "university": "rgtu"
    },
    {
        "id": 11,
        "name": "Babloo",
        "rollNumber": "0126CS11",
        "university": "rgtu"
    },
    {
        "id": 12,
        "name": "Ga",
        "rollNumber": "0126CS12",
        "university": "rgtu"
    }
]

DELETE  API – http://localhost:9091/student/deleteall

Spring Data JPA deleteAll() Vs deleteAllInBatch()

Let’s perform saveall again and delete all records using deleteAllInBatch().

Spring Data JPA deleteAll() Vs deleteAllInBatch()

That’s all about Spring Data JPA deleteAll() Vs deleteAllInBatch()  Example.

You may like.

Other Spring Data JPA and Hibernate tutorials.

Spring Data JPA JpaRepository() docs.