@Query annotation using like %?1%

≡放荡痞女 提交于 2019-12-18 06:59:09

问题


I'd like to write a query like this

@Query("select p from Product p where p.name = ?1 or p.desc like %?1%")

but it gives me the exception

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: % near line 1,

I tried replacing % with '%' or concatenating the query string like this: "select ... like '%'" + "?1" + "'%'" but with no luck, please help me


回答1:


If you are using Spring Data JPA version 1.3.1 or later you need to do the following:

@Query("select p from Product p where p.name = :name or p.desc like %:name%")
public List<Product> searchByName(@Param("name") String name);

Check out this blog post for more details

Prior to Spring Data JPA 1.3.1, you could not use % in the @Query annotation, but instead you needed to add it in the argument itself




回答2:


use the CONCAT as following:

@Query("select p from Product p where p.name = ?1 or p.desc like CONCAT('%',?1,'%') ")



回答3:


Use :. And you can use identifiers.

@Query("select p from Product p where p.name = :productName or p.desc like :productDescription")

And then

query.setParameter("productName", theName);

Check out the JPQL specification to learn the differences between JPQL and SQL.

UPDATE: In the case of the LIKE operator, the % are put in the value, not in the JPQL.

query.setParameter("productDescription", "%" + partialDescription + "%");


来源:https://stackoverflow.com/questions/23326642/query-annotation-using-like-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!