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

标签 java sql hibernate jpa

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

最佳答案

你用的是原生查询,原生查询好像根本就没有列表参数:

Set list parameter to native query

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

您必须手动连接 SQL。

关于java - 如何在 JPA 中创建成对列表作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249140/

相关文章:

java - 在 JFrame 上定位组件

php - 如何在 PHP 中查找 "related items"

sql - 替换 SQL Server XML 中的属性名称

MySQL 错误 : Inserting form data into Database

spring - 使用Struts2 Spring Hibernate进行异常处理-做到这一点的最佳方法

java - Entitymanager 为 null spring JPA 配置

java - 无法在 thymeleaf 中显示 byte[] 图像

java - 在 Eclipse 中使用 Maven 就地提供资源

java - 如何在 Eclipse 中更改 XML 文件的制表符大小?

java - 将 Struts 1 中的 Action 转换为 Struts 2 等效项