Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bulk delete from element collection in jpa

I'm using jpa 2.0 and I have the following entity:

@Entity
public class Folder{

    @ElementCollection
    @CollectionTable(name="folder_files")
    private Set<String> files;      
    // .....
 }

Given a file name, I would like to delete all entries where files == theGivenFileName. In sql it would be something like this:

Delete from folder_files where files = XXX

Is there a way to perform this query using criteria-api? If not, is there a way to perform this query using jpql?

UPDATE: I think my question was not clear enough: Since jpql uses entities (and not tables) I cannot just perform the sql written above plus since I'm using @ElementCollection I don't know how to address this variablr or even deal with it. I would like to delete all entries in that collection (in my case, the files set) which holds a given value, from all entities. Is that possible using jpql or (even better) criteria-api?

like image 494
Noam Avatar asked May 07 '12 11:05

Noam


People also ask

How do I delete a record using JPA?

We can use the JPA method deleteById() for deleting the record of the particular primary key.

What is the return type of delete method in JPA repository?

A derived delete query must start with deleteBy, followed by the name of the selection criteria. These criteria must be provided in the method call. The return value, of type long, indicates how many records the method deleted. Persisting and deleting objects in JPA requires a transaction.

What is the full form of JPQL?

The Java Persistence query language (JPQL) is used to define searches against persistent entities independent of the mechanism used to store those entities.

What is @ElementCollection?

JPA 2.0 defines an ElementCollection mapping. It is meant to handle several non-standard relationship mappings. An ElementCollection can be used to define a one-to-many relationship to an Embeddable object, or a Basic value (such as a collection of String s).


1 Answers

The Delete FROM clause requires an Entity, so there is no way to delete from an element collection from what I understand.

You can use a native SQL query, or you can map the element collection as a OneToMany to an Entity instead.

like image 149
James Avatar answered Oct 24 '22 14:10

James