如何使用bulkUpdate批量删除 [英] How to batch delete using bulkUpdate

查看:690
本文介绍了如何使用bulkUpdate批量删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的用户/角色设置,带有一个user_role连接表。我尝试使用Spring的HibernateTemplate来批量删除所有这样的锁定用户:

  getHibernateTemplate()。bulkUpdate(delete from用户where locked =?,true); 

如果被删除的用户没有任何角色(user_role表中没有记录),则所有内容没事的;但是,如果用户确实有角色记录,我会收到以下错误:


违反了完整性约束 - 子
记录找到


角色在User.java中是这样定义的:



<$ p $ (name =user_role,joinColumns = {@JoinColumn(name =user_id)},inverseJoinColumns = @JoinColumn(name); @MoinToMany(fetch = FetchType.EAGER)
@JoinTable =role_id))
private Set< Role> roles = new HashSet< Role>();

那么即使用户有子记录,我如何批量删除用户呢?谢谢!根据JPA规范,批量删除操作不会级联到相关实体 / b>


4.10批量更新和删除操作



批量更新和删除操作
适用于单一实体
类(与其子类一起,如果有的话
)的实体。在
FROM或UPDATE子句中只能指定一个实体摘要
模式类型。



...



删除操作仅适用于指定类的
实体和
的子类。 它不会将
级联到相关实体


但是,我希望JPA提供者处理连接表。可悲的是,Hibernate没有,这是记录在 HHH-1917 。恐怕你必须回退本机SQL来自己清理连接表,或者在模式中使用级联外键。


I have a common User / Role setup, with a user_role join table. I'm trying to use Spring's HibernateTemplate to mass delete all locked users like this:

getHibernateTemplate().bulkUpdate("delete from User where locked=?", true);

If the user being deleted does not have any roles (no record in the user_role table), then everything goes fine; however if the user does have a role record, I'm getting the following error:

integrity constraint violated - child record found

Roles are defined in User.java like this:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<Role>();

So how can I batch delete users even if a user has child records? Thanks!

解决方案

Bulk delete operations are not cascaded to related entities as per the JPA specification:

4.10 Bulk Update and Delete Operations

Bulk update and delete operations apply to entities of a single entity class (together with its subclasses, if any). Only one entity abstract schema type may be specified in the FROM or UPDATE clause.

...

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

However, I'd expect the JPA provider to deal with join tables. Sadly, Hibernate doesn't and this is logged in HHH-1917. I'm afraid you'll have to fall back on native SQL to clean up the join table yourself or to use cascading foreign keys in the schema.

这篇关于如何使用bulkUpdate批量删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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