我正在尝试在 Spring Data JPA 中的查询中使用动态列名和值
interface CustomFooRepository {
fun findByValueIgnoreCase(query: String, type: RequestType): List<Foo>
}
class CustomFooRepositoryImpl(
@PersistenceContext private val entityManager: EntityManager
) : CustomFooRepository {
override fun findByValueIgnoreCase(query: String, type: RequestType): List<Foo> {
val column = when (type) {
RequestType.first_name -> "first_name"
RequestType.last_name -> "last_name"
RequestType.email -> "email"
}
val sql = """
SELECT
*,
SIMILARITY(:column, :query) AS score
FROM foo
WHERE :column iLIKE %:query%
ORDER BY score DESC NULLS LAST, :column
LIMIT 20;
"""
val constructedQuery = entityManager.createNativeQuery(sql, Foo::class.java)
constructedQuery.setParameter("column", column)
constructedQuery.setParameter("query", query)
return constructedQuery.resultList as List<Foo>
}
}
interface FooRepository : JpaRepository<Foo, Long>, CustomFooRepository
但这让我
org.springframework.dao.InvalidDataAccessResourceUsageException:没有命名参数':query%'的参数
为什么?
您不能
%
在查询字符串内部进行连接。必须在外部进行连接。最好的解决方案是添加一个新参数:
constructedQuery.setParameter("queryWildcard", "%" + query + "%")
因此,您最终的 SQL 文字将是: