Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to batch delete using bulkUpdate

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!

like image 547
SamS Avatar asked Apr 09 '09 17:04

SamS


People also ask

What is bulk delete?

The bulk deletion feature helps you to maintain data quality and manage the consumption of system storage by deleting data that you no longer need. For example, you can delete the following data in bulk: Stale data. Data that is irrelevant to the business.

How do you quickly delete records in Oracle?

If you are not licensed for Oracle partitioning, and you load your rows in-order, you could roll-your-own partitioning, using different tables names for each partition. Parallelize deletes - Oracle parallel DML includes delete statements and you can parallelize large deletes for faster performance.

What is bulk update?

A bulk update definition specifies a number of conditions and a single update function. A policy must satisfy all the specified conditions in order for it to updated by the function. Bulk updates are executed through a global activity. The bulk update definition code is a parameter of this activity.


1 Answers

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.

like image 120
Pascal Thivent Avatar answered Sep 26 '22 00:09

Pascal Thivent