2012-12-19 6 views
8

Tôi đang cố gắng viết truy vấn JPQL sẽ xóa tất cả PlaylistItem -s tham chiếu đến ArtContent -s cụ thể theo số ArtContent ID.Làm thế nào để xóa các mục bằng ID-s của mục con của chúng trong Hibernate?

Tôi cố gắng này:

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

nhưng nó ném một ngoại lệ:

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

là gì dễ hiểu, vì không có setParameter phương pháp dùng một mảng làm tham số. Vậy cách tốt nhất để giải quyết vấn đề như thế nào?

giản định nghĩa lớp:

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

Trả lời

7

Bạn có thể tiếp tục sử dụng .setParameter nhưng bạn cần làm cho giá trị mở rộng Bộ sưu tập (như một ArrayList) thay vì sử dụng loại mảng. Có thể chỉ cần thay đổi thành:

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

Đúng vậy! Cảm ơn rất nhiều! – Anke

+0

Làm việc tốt cho tôi, cảm ơn! – kospol

1

Hãy thử setParameterList để thay thế.

Edit:

Xin lỗi, cho JPA chuyển nó sang một Bộ sưu tập (Arrays.asList(arrayOfLongs)) và chỉ sử dụng setParameter.

Chỉnh sửa 2: Bị đánh vào cú đấm!

+0

Xin cảm ơn, nhưng setParameterList là một phương thức của org.hibernate.Query và tại đây tôi có javax.persistence.Query. – Anke

+0

Có, Bộ sưu tập đã thực hiện công việc :) – Anke