如何使用 REST API 删除多条记录

How do I delete multiple records using REST API

刚开始接触Springboot,开发了按ID删除记录的资源,现在喜欢删除选中的多条记录。 示例:我喜欢在单个请求中删除 10 条记录中的 3 条记录

控制器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);
    }

服务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);
    }

JPAClass:

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

请教我如何删除选定的多条记录。

首先你需要创建一个jpa查询方法,将所有属于id的记录。

public interface UserContentManageRepository extends JpaRepository<UserContentManage, Integer> {
       List<UserContentManage> findAllById(Integer id);  
}

之后就可以对List做deleteAll()操作了。

@Transactional(rollbackFor = Exception.class)
public void deleteContentManage(int contentmanageId) {

    List<UserContentManage> userContentManageList = userContentManageRepository.findAllById(contentmanageId);
    if(userContentManageList == null){
        log.error("Exception occurs while not found content manage ({}) in deletion. ");
        throw new GenericBadException(StaffNotificationExceptionEnum.CONTENT_MANAGE_NOT_FOUND_EXCEPTION);
    }

    userContentManageRepository.deleteAll(userContentManageList );
}

你可以像

一样在Repository中添加方法
@Modifying
@Transactional
@Query("delete from UserContentManagep where u.id in(:integers)")
void deleteByIdIn(List<Integer> integers);

如果您在项目中实现了软删除,您可以像下面这样进行软删除:

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

从服务 class 你可以尝试调用 as

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

完整的工作示例:

@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);

}