When building applications, there might be scenarios where you need to delete multiple entities based on a list of their identifiers. Using Spring Data JPA, this can be achieved seamlessly, and in this blog post, we'll explore how.
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
Let's create an PersonRepository
interface that extends the JpaRepository
interface
from Spring Data JPA:
import com.springdatajpa.springboot.entity.Person;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person, Long> {
}
With the repository in place, Spring Data JPA provides a convention-based method to delete entities by their IDs:
void deleteByIdIn(List<Long> ids);
It's that simple! The deleteByIdIn
is a derived delete query, which means
that Spring Data JPA
automatically creates the necessary query for deleting multiple entities based on their IDs.
To ensure transactional integrity and separation of concerns, wrap your data operations inside a service:
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
@Transactional
public void deletePersonsByListOfIds(List<Long> ids) {
personRepository.deleteByIdIn(ids);
}
}
The @Transactional
annotation ensures that all deletion operations in the
list occur within a
single transaction. If an error arises with any of the deletions, the entire operation will be rolled back,
maintaining data consistency.
With Spring Boot, it's straightforward to test the deletion logic:
@SpringBootTest
public class PersonServiceTest {
@Autowired
private PersonService personService;
@Autowired
private PersonRepository personRepository;
@Test
public void testDeleteByListOfIds() {
// Given: Initial data
Person john = personRepository.save(new Person("John", "123 Elm Street"));
Person jane = personRepository.save(new Person("Jane", "456 Maple Avenue"));
List<Long> idsToDelete = Arrays.asList(john.getId(), jane.getId());
// When: Deleting persons by IDs
personService.deletePersonsByListOfIds(idsToDelete);
// Then: Assert that the persons are deleted
assertTrue(personRepository.findById(john.getId()).isEmpty());
assertTrue(personRepository.findById(jane.getId()).isEmpty());
}
}
Spring Data JPA's out-of-the-box capabilities are a boon for developers. It simplifies many database operations, allowing developers to focus more on the business logic. When deleting entities using a list of IDs, it is not just about the simplicity but also about the performance gains, as the framework can optimize the deletion process.