jpa like模糊查询

 一楼问: 
 
Hi,

I'm trying to use the LIKE statement with JPA. What I want to do is get all the items that have a name that matchs the keyword 'og' for example ('Dog', 'Big dog'...). If I write that :

query = em.createQuery("SELECT i FROM Item i WHERE i.name LIKE :keyword");
query.setParameter("keyword", keyword);

That will take the items that have the exact keword (in my example only 'og' will appear). I've tried to use the wildcards % but id doesn't work :

query = em.createQuery("SELECT i FROM Item i WHERE i.name LIKE '%:keyword%'");
query = em.createQuery("SELECT i FROM Item i WHERE i.name LIKE %:keyword%");

Does anybody knows how to use the LIKE statement with wildcards ? And by the way, is there a way to ignore the case of my keyword ('og' or 'OG' should give the same result).

Thanks,

Antonio Goncalves
 
 

二楼:

 

 

 
    
Hello Antonio,

Can you not use
query = em.createQuery("SELECT i FROM Item i WHERE UPPER(i.name) LIKE UPPER(:keyword)");
query.setParameter("keyword","%"keyword"%");
query.getResultList();

Best Regards,
Chris
 
 三楼: 
    
Hi Chris. It doesn't work with the UPPER keyword. Here is the error that I've got :

Caused by: Exception [TOPLINK-8025] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.EJBQLException
Exception Description: Syntax error parsing the query [SELECT i FROM Item i WHERE UPPER(i.name) LIKE UPPER(:keyword) ORDER BY i.name], unexpected token [LIKE].
|#]

Any idea ?

Otherwise, the wildcard works fine :

query = em.createQuery("SELECT i FROM Item i WHERE i.name LIKE :keyword");
query.setParameter("keyword","%"keyword"%");
query.getResultList();
 
 

四楼:

 

  
Hello,

Sorry, looks like i was wrong on the UPPER(:keword) portion. The spec states:
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
"The pattern_value is a string literal or a string-valued input parameter"

So you will have to call toUpperCase() on the string you pass into the query ie:
query.setParameter("keyword","%"keyword.toUpperCase()"%");

Best Regards,
Chris
 
 

最终写法:

 

 
Click to report abuse...  Click to reply to this thread  
Thanks, it works fine like that

query = em.createQuery("SELECT i FROM Item i WHERE UPPER(i.name) LIKE :keyword ORDER BY i.name");
query.setParameter("keyword", "%" + keyword.toUpperCase() + "%");

Antonio

 
我的
错误写法:sql.append(" and s.idCard like %?% ");
paraml.add(stuff.getIdCard().trim());

正确应该是:
   sql.append(" and s.idCard like ? ");
   
   paraml.add("%"+stuff.getIdCard().trim()+"%");
  

转自:http://forums.oracle.com/forums/thread.jspa?threadID=423742

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值