首页 > 解决方案 > Spring data JPA Repositories + hibernate-types:如何使用 jpa 查询按数组过滤?

问题描述

我有一个 Spring Boot 项目,其中Entity声明了带有适当@TypeDef注释的ListArrayType. 它工作得很好:我可以创建实体并按其他字段过滤。

我有一个workflows字段responsible_users是 Postgres 字符串数组的表。我想通过这个字段查询。这个原始查询有效:

SELECT id FROM workflows 
WHERE
    responsible_users @> ARRAY['urn:...', '...'] AND 
    responsible_users <@ ARRAY['urn:...', '...'];

但我无法使用查询注释执行类似的查询:

@Query("""
    SELECT w.* from workflows w 
    WHERE 
            w.project_origin = :projectOrigin 
        AND
            w.responsible_users @> ARRAY[:responsibleUsers] AND
            w.responsible_users <@ ARRAY[:responsibleUsers]
""", nativeQuery = true)
fun blabla(
    @Param("projectOrigin") projectOrigin: String,
    @Param("responsibleUsers") responsibleUsers: List<String>
) : List<Workflow>

因为插值后查询看起来像:

SELECT w.* from workflows w
WHERE
        w.project_origin = $1
    AND
        w.responsible_users @> ARRAY[($2)] AND
        w.responsible_users <@ ARRAY[($3)]

我应该如何通过列表?Spring Data JPA 存储库是否可行?

编辑 1

我已经手动执行了查询:


@Autowired
lateinit var em: EntityManager

fun findWorkflowByProjectOriginAndResponsibleUsers(
    projectOrigin: String,
    responsibleUsers: Collection<String>
): Workflow? {
    val searchArray = "{" + responsibleUsers.joinToString(",") + "}"

    @Language("PostgreSQL")
    val query = """
        SELECT w.* from workflows w
        WHERE
            w.project_origin = :projectOrigin
        AND
            w.responsible_users @> CAST(:qwe as text[]) AND
            w.responsible_users <@ CAST(:qwe as text[])
    """.trimIndent()
    return em.createNativeQuery(
        query,
        Workflow::class.java
    )
        .setParameter("projectOrigin", projectOrigin)
        .setParameter(
            "qwe",
            searchArray
            // TypedParameterValue(StringArrayType.INSTANCE, workflowCreateDTO.responsibleUsers.toTypedArray())
        )
        .singleResult as Workflow?
}

无论如何,这似乎不是一个答案,因为现在是 2020 年。

(顺便说一句,使用 StringArrayType 的技巧不起作用)

标签: springpostgresqlhibernatespring-data-jpa

解决方案


推荐阅读