How do I delete multiple records using REST API

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How do I delete multiple records using REST API on this date .

Am new to Springboot, I have develop the resource to delete the record by ID, now I like delete selected multiple records. Example: I like to delete 3 records out of 10 records in single request

Controller class:

 @ApiHeader(
            apiOperation = "delete a Content Manage by id",
            apiOperationNotes = "delete a Content Manage by id"
    )
    @PostMapping(value = UriConstants.CONTENT_MANAGE_DELETE)
    @ResponseStatus(HttpStatus.OK)
    public void deleteContentManage(@PathVariable("content_manage_id") int contentmanageId) {
        contentManageService.deleteContentManage(contentmanageId);
    }

Service Class:

  @Transactional(rollbackFor = Exception.class)
    public void deleteContentManage(int contentmanageId) {
        Optional<UserContentManage> optional = userContentManageRepository.findById(contentmanageId);
        if(!optional.isPresent()){
            log.error("Exception occurs while not found content manage ({}) in deletion. ", contentmanageId);
            throw new GenericBadException(StaffNotificationExceptionEnum.CONTENT_MANAGE_NOT_FOUND_EXCEPTION);
        }
        userContentManageRepository.deleteById(contentmanageId);
    }

JPA Class:

public interface UserContentManageRepository extends JpaRepository<UserContentManage, Integer> {
}

please suggest me how do I delete selected multiple records.

Answer

You can add method in Repository like

@Modifying
@Transactional
@Query("delete from UserContentManagep where u.id in(:integers)")
void deleteByIdIn(List<Integer> integers);

If you have implemented soft delete in project you can do soft delete like below:

@Modifying
@Transactional
@Query("update  UserContentManagep u set u.active = false where u.id in(:integers)")
void softDeleteAllIds(List<Integer> integers);

And from service class you can try to call as

public void deleteAllBYIds(List<Integer> integers) {
    personRepository.deleteByIdIn(integers);
}

Fully working example:

@RestController
@RequestMapping("/person")
public class PersonController {

    private final PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @GetMapping
    public Iterable<Person> list() {
        return personService.list();
    }

    @PostMapping
    public Person create(@RequestBody Person car) {
        return personService.save(car);
    }


    @DeleteMapping
    public String delete(@RequestParam("ids") List<Integer> ids) {
        System.out.println("deleting");
        personService.deleteAllBYIds(ids);
        return String.join(",", ids.stream().map(value ->  Integer.toString(value)).collect(Collectors.toList()));
    }


}

@Getter
@Setter
@ToString
@Entity
@Where(clause = "active = true") // selecting only items which are active
class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private boolean active = true;
}

@Service
class PersonService {
    private final PersonRepository personRepository;

    @Autowired
    PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @Transactional
    public Person save(Person person) {
        return personRepository.save(person);
    }

    @Transactional(readOnly = true)
    public Iterable<Person> list() {
        return personRepository.findAll();
    }

    @Transactional(readOnly = true)
    public PersonDTO findPersonByName(String name) {
        return personRepository.findPersonsByName(name);
    }

    public void deleteAllBYIds(List<Integer> integers) {
//        personRepository.deleteByIdIn(new ArrayList<>(integers));
        personRepository.softDeleteAllIds(integers);

        System.out.println("deleted adnlakdjakldlas");
    }
}

interface PersonDTO {
    String getName();

    Collection<String> getPersonEvents();
}

@Repository
interface PersonRepository extends CrudRepository<Person, Integer> {
    PersonDTO findPersonsByName(String name);

    @Modifying
    @Transactional
    @Query("delete from Person p where p.id in(:integers)")
    void deleteByIdIn(List<Integer> integers);

    @Modifying
    @Transactional
    @Query("update  Person p set p.active = false where p.id in(:integers)")
    void softDeleteAllIds(List<Integer> integers);

}