Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete items by ID-s of their child item in Hibernate?

I'm trying to write an JPQL query which would delete all PlaylistItem-s refering to specific ArtContent-s by ArtContent IDs.

I tried this:

public int deleteItemsByContentIds(Long[] contentIds) {
    EntityManager em = getEntityManager();
    int result = em.createQuery(
    "delete from PlaylistItem where artContent.id in (:idsArray) ")
    .setParameter("idsArray", contentIds).executeUpdate();

    return result;
}

but it throws an exception:

Servlet.service() for servlet RemoveContentServlet threw exception: 
javax.ejb.EJBException: java.lang.IllegalArgumentException: 
Encountered array-valued parameter binding, but was expecting [java.lang.Long]

What is understandable, because there is no setParameter method taking an array as an argument. So what is the best way to solve such an issue?

Simplified class definition:

@Entity
public class PlaylistItem implements Serializable {

@Id
@GeneratedValue
private Long id;

private int position;

@ManyToOne(optional = false)
@JoinColumn(name = "PLAYLIST_ID")
private Playlist playlist;

@ManyToOne(optional = false)
@JoinColumn(name = "ART_CONTENT_ID")
private ArtContent artContent;

...

}

@Entity
public class ArtContent implements Serializable {

@Id
@GeneratedValue
private Long id;
...
}
like image 261
Anke Avatar asked Dec 19 '12 14:12

Anke


2 Answers

You can keep using .setParameter but you need to make the value extend a Collection (like an ArrayList) instead of using an array type. Maybe just change to:

public int deleteItemsByContentIds(Long[] contentIds) {
    EntityManager em = getEntityManager();
    int result = em.createQuery(
    "delete from PlaylistItem where artContent.id in (:idsArray) ")
    .setParameter("idsArray", Arrays.asList(contentIds)).executeUpdate();

    return result;
}
like image 166
Jeff Avatar answered Sep 17 '22 21:09

Jeff


Try setParameterList instead.

Edit:

Sorry, for JPA convert it to a Collection (Arrays.asList(arrayOfLongs)) and just use setParameter.

Edit 2: Beaten to the punch!

like image 20
Matt Brock Avatar answered Sep 17 '22 21:09

Matt Brock