8

我正在尝试编写一个 JPQL 查询,该查询将删除所有通过ID PlaylistItem引用特定ArtContent-s 的 -s 。ArtContent

我试过这个:

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;
}

但它会引发异常:

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

这是可以理解的,因为没有setParameter将数组作为参数的方法。那么解决此类问题的最佳方法是什么?

简化的类定义:

@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;
...
}
4

2 回答 2

7

您可以继续使用.setParameter,但您需要使值扩展集合(如 ArrayList),而不是使用数组类型。也许只是更改为:

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;
}
于 2012-12-19T15:06:01.483 回答
1

试试setParameterList吧。

编辑:

抱歉,对于 JPA,将其转换为 Collection ( Arrays.asList(arrayOfLongs)) 并使用setParameter.

编辑2:被打败了!

于 2012-12-19T15:00:56.740 回答