如何在LIKE jpql查询中使用Quute?

问题描述 投票:0回答:1

因此,我正在尝试编写一些自定义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%'

对我来说,这很好,但是firstNamesecondName表列可能包含带有'之类的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();
    }      
}

我如何搜索包含单仲裁'的值?

java spring hibernate jpql
1个回答
0
投票

我建议您在创建查询时使用索引或命名参数。这样可以解决您的问题,因为它将自动转义任何命令字符。

类似这样的东西:

em.createQuery("SELECT t FROM TestEntity t WHERE t.fullName LIKE :fullName " 
                + "OR t.firstName  LIKE :firstName " 
                + "OR t.firstName  LIKE :lastName " 
                + "OR t.lastName LIKE :firstName " 
                + "OR t.lastName LIKE :lastName") 
                .setParameter("firstName", firstName) 
                .setParameter("lastName", lastName) 
                .setParameter("fullName", fullName)
                .getResultList();

我假设您是从服务层的方法参数中获取名字,姓氏,全名。

此外,由于用户可以通过REST端点注入恶意代码,因此当前的实现还使您的应用容易受到SQL / JPQL攻击。

有关SQL注入的更多信息:https://www.baeldung.com/sql-injection

使用命名和索引参数创建查询:https://docs.oracle.com/javaee/6/tutorial/doc/bnbrg.html

© www.soinside.com 2019 - 2024. All rights reserved.