like子句JPQL中的参数

84 java jpa eclipselink jpql sql-like

我正在尝试使用like子句编写JPQL查询:

LIKE '%:code%'
Run Code Online (Sandbox Code Playgroud)

我想有代码= 4并找到

455
554
646
...

我无法通过 :code = '%value%'

namedQuery.setParameter("%" + this.value + "%");
Run Code Online (Sandbox Code Playgroud)

因为在另一个地方我不需要:value%chars 包裹.有帮助吗?

shi*_*ter 165

如果你这样做

LIKE :code
Run Code Online (Sandbox Code Playgroud)

然后呢

namedQuery.setParameter("code", "%" + this.value + "%");
Run Code Online (Sandbox Code Playgroud)

然后价值保持从'%'符号.如果您需要在同一查询中的其他位置使用它,只需使用"代码"以外的其他参数名称.

  • 对于记录,这不会让您对JPQL注入攻击持开放态度,因为this.value会自动为您正确转义. (9认同)
  • 这个"%"+ this.value +"%"`是被转义的. (2认同)
  • 我如何使这个不区分大小写? (2认同)

gav*_*koa 54

我没有为所有查询使用命名参数.例如,在JpaRepository中使用命名参数是不常见的.

解决方法我使用JPQL CONCAT函数(此代码模拟开头):

@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
    private static final String QUERY = "select b from Branch b"
       + " left join b.filial f"
       + " where f.id = ?1 and b.id like CONCAT(?2, '%')";
    @Query(QUERY)
    List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}
Run Code Online (Sandbox Code Playgroud)

我在优秀的文档中找到了这种技术:http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html

  • 注意:CONCAT(?2, '%') 将在参数的末尾添加 '%',使用 CONCAT('%', ?2, '%') 将其添加到参数的开头和结尾。 (3认同)

Dav*_*son 7

您可以使用JPA LOCATE函数.

LOCATE(searchString,candidateString [,startIndex]):返回candidateString中searchString的第一个索引.职位从1开始.如果找不到该字符串,则返回0.

仅供参考:我最热门谷歌搜索的文档反转了参数.

SELECT 
  e
FROM 
  entity e
WHERE
  (0 < LOCATE(:searchStr, e.property))
Run Code Online (Sandbox Code Playgroud)