8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JPAで%(ワイルドカード)を含んだlike句をsetParameterする

Posted at

JPAで%(ワイルドカード)を含んだlike句をsetParameter()する時に少し困りました。


困った事

こんなSQLを実行したい場合。

SQL
select * from user where user.name like '%keyword%';

JPQLで書くとこんな感じになりそうですが・・・

JPQL
TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE u.name LIKE %:keyword%");
query.setParameter("keyword", keyword);

もしくは、シグルクォートで囲ってこんな感じ。

JPQL
TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE u.name LIKE '%:keyword%'");
query.setParameter("keyword", keyword);

どちらも実行すると下記のようなエラーが出てしまいます :cold_sweat:

ERROR o.h.hql.internal.ast.ErrorCounter - line 1:109: unexpected token: % 
antlr.NoViableAltException: unexpected token: %

解決策

こんな時はこうやるとうまくいきます.

JPQL
TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE u.name LIKE :keyword");
query.setParameter("keyword", "%" + keyword + "%");

さらに英語の大文字・小文字の違いも吸収したい場合は、こうします。

JPQL
TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u WHERE UPPER(u.name) LIKE UPPER(:keyword)");
query.setParameter("keyword", "%" + keyword + "%");
8
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?