How to delete a list of entities

Viewed 4283

I have a JPA query to delete selected entities which is stored in a list. I am currently deleting the entities in a loop via the in built JPA delete() method 1 by 1. Is there a way to just pass in the list instead of looping it?

Current implementation that works but looping to delete 1 by 1. I need the initial query to get list of entities for other reasons thus not looking to change that. Just a way to pass in the list of entiies to be deleted. Please advice. Thanks.

Note: This is with Java 8 and Spring 4.3 if it matters.

@GetMapping("/delete/{name}/{count}")
public String delete(@PathVariable String name, @PathVariable int count){
    boolean isDelete = true;
    while (isDelete){
        //1st query
        List<PersonEntity> results = personService.get(name, count);
        if(results != null && !results.isEmpty()){
            System.out.println("Deleting following: ");
            //2nd query
            results.forEach(p -> {
                System.out.println(p.getName());
                personService.delete(p);
            });
        } else {
            isDelete = false;
        }
    }
    return "Done!";
}
1 Answers

You can try something like this:

List<PersonEntity> results = personService.get(name, count);
if(results != null && !results.isEmpty()) {
    List<Integer> personIds = results.stream()
        .map(personIds)
        .collect(Collectors.toList());
    personService.deleteManyById(personIds);

In your service:

public void deleteManyById(List<Integer> ids) {
    personRepository.deleteByIdIn(ids);
}

In your repo (assuming it's a spring JpaRepository):

void deleteByIdIn(List<Integer> ids);

Just be aware of the fact that dbs have a limit in the number of parameters you can pass in a IN condition

Related