如何处理Spring Data JPA中的ID数组进行批量删除? [英] How do you handle with bulk deleting by an array of IDs in Spring Data JPA?

查看:139
本文介绍了如何处理Spring Data JPA中的ID数组进行批量删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个类User,我从 jsp html 获得了 array 的请求数据.

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

列出此 Integer [] arr = [5,6,9,10,62,52,21]

然后我使用两种方法来完成批量删除操作.

and then I use two methods to finish bulking deleting action.

@Transactional
@Override
public void deleteUser(Integer id) {

    oneRepository.delete(id);
}


@Transactional
@Override
public void deleteSomeUser(Integer[] ids) {

    for (Integer id : ids) {

        deleteUser(id);

    }

}

我想知道这是否是完成此操作的更有效方法.

I want to know that if it's a more efficient method to finish this action.

您可以看到我的日志:好像不太好!

you can see my logs: it seems not so good!

[94, 95, 91, 92, 93]
Hibernate: 
    delete 
    from
        sshh_user 
    where
        ID=?


Hibernate: 
    delete 
    from
        sshh_user 
    where
        ID=?



Hibernate: 
    delete 
    from
        sshh_user 
    where
        ID=?



Hibernate: 
    delete 
    from
        sshh_user 
    where
        ID=?



Hibernate: 
    delete 
    from
        sshh_user 
    where
        ID=?



Hibernate: 
    select
        count(practice0_.ID) as col_0_0_ 
    from
        sshh_user practice0_

推荐答案

假设您有一个 UserRepository ,例如:

public interface UserRepository extends JpaRepository<User, Integer> {}

然后,您可以在 UserRepository 中添加如下所示的修改查询方法:

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<Integer> 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 (? , ? , ?)

还要注意 public 建议方法时,> Self Invocation 问题.

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

这篇关于如何处理Spring Data JPA中的ID数组进行批量删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆