【发布时间】:2020-02-05 04:21:15
【问题描述】:
所以,我正在尝试编写一些自定义 JPQL 查询构建器。 我有一个类似的端点:
/api/library/authors/search?query=test tested
在服务层,这个query 参数将被转换为类似JPQL 查询的smth:
SELECT t FROM Author t WHERE t.fullName LIKE '%test tested%'
OR t.firstName LIKE '%test%'
OR t.firstName LIKE '%tested%'
OR t.secondName LIKE '%test%'
OR t.secondName LIKE '%tested%'
它对我来说非常好用,但是 firstName 或 secondName 表列可能包含带有引号 ' 的值,例如 O'Hara。然后就不行了。
/api/library/authors/search?query=Tes O'Ha
所以,我尝试在查询中将' 替换为双引号",如下所示:
SELECT t FROM Author t WHERE t.fullName LIKE "%Tes O'Ha%"
OR t.firstName LIKE "%Tes%"
OR t.firstName LIKE "%O'Ha%"
OR t.secondName LIKE "%Tes%"
OR t.secondName LIKE "%O'Ha%"
我遇到了一个异常:
org.hibernate.QueryException: unexpected char: '"'
我还尝试替换 \' 上的 ' 和 \" 上的 "。所有它都不起作用并抛出异常......
我正在使用 EntityManager 执行此查询:
@Repository
public class SearchFor {
@PersistenceContext
private EntityManager entityManager;
public List execute(String query) {
return entityManager.createQuery(query).getResultList();
}
}
如何搜索包含单引号 ' 的值?
【问题讨论】:
-
你试过转义 ***LIKE "%Tes O\'Ha%" *** 吗?
标签: java spring hibernate jpql