【问题标题】:How in JPA create list of pairs as parameter?如何在 JPA 中创建对列表作为参数?
【发布时间】:2015-09-23 19:03:42
【问题描述】:

在我的 Java 应用程序中,我想创建 SQL 查询,最终将如下所示:

SELECT * FROM my_table t WHERE (t.a, t.b) IN ((a1,b1),(a2,b2),(a3,b3), ... )

如何生成?

我的代码如下所示:

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

【问题讨论】:

  • 原生查询没有 NAMED 参数。它具有位置参数(如果您重视可移植性)。根据参数的数量生成 SQL。

标签: java sql hibernate jpa


【解决方案1】:

你使用的是原生查询,似乎原生查询根本没有list参数:

Set list parameter to native query

How to use a dynamic parameter in a IN clause of a JPA named query?

您必须手动连接 SQL。

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 2014-10-16
    • 2023-03-12
    • 2018-06-25
    • 2023-01-04
    • 2021-06-04
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多