How do you handle with bulk deleting by an array of IDs in Spring Data JPA?

前端 未结 4 827
星月不相逢
星月不相逢 2021-02-04 05:15

Now I have a class User, I get a request data of an array from the jsp or html.

list this Integer[] arr=[5,6,9,10,62,52,21]

4条回答
  •  遇见更好的自我
    2021-02-04 05:31

    Suppose you have a UserRepository like:

    public interface UserRepository extends JpaRepository {}
    

    Then you can add a modifying query method like following into your UserRepository:

    /**
     * Delete all user with ids specified in {@code ids} parameter
     * 
     * @param ids List of user ids
     */
    @Modifying
    @Query("delete from User u where u.id in ?1")
    void deleteUsersWithIds(List ids);
    

    Finally you can change your bulk deletion service like following:

    @Transactional
    @Override
    public void deleteSomeUser(Integer[] ids) {
        oneRepository.deleteUsersWithIds(Arrays.asList(ids));
    }
    

    This will generate a delete query like:

    Hibernate: delete from users where id in (? , ? , ?)
    

    Also be aware of Self Invocation issues when you calling one public advised method from another one.

提交回复
热议问题