如何在JPA中创建对列表作为参数?

M31*_*314 5 java sql hibernate jpa

在我的Java应用程序中,我想创建SQL查询,最终将看起来像这样:

SELECT * FROM my_table t WHERE (t.a, t.b) IN ((a1,b1),(a2,b2),(a3,b3), ... )
Run Code Online (Sandbox Code Playgroud)

如何生成它?

我的代码看起来像这样:

public List<MyEntity> getMyEntity(List<Long> alist, List<Long> blist) {

    String stringQuery = "SELECT * FROM my_table t WHERE (t.a , t.b) in (:alist, :blist)"; 

    // This is kinda how I whould like my query to look, but I guess I will generate something like:
    // SELECT * FROM my_table t WHERE (t.a, t.b) IN ((a1, a2, a3, ...), (b1, b2, b3, ...))
    // which isn't the same and it isn't what I want 

    Query query = getEntityManager().createNativeQuery(stringQuery, MyEntity.class);

    // I'm using native query because in my aplication above query is in fact much more complicated, 
    // and I can't use standard JPA query. I cut those parts here, because they aren't directly related to my problem
    // in the other way that they force to use native query.

    query.setParameter("alist", alist);
    query.setParameter("blist", blist);

    return query.getResultList();
}
Run Code Online (Sandbox Code Playgroud)

pde*_*dem 1

您使用本机查询,似乎本机查询根本没有列表参数:

将列表参数设置为本机查询

如何在 JPA 命名查询的 IN 子句中使用动态参数?

您必须手动连接 SQL。