Hibernate实现模糊查询的方法

大家都知道使用本地SQL进行模糊查询用关键字 LIKE 对于在hibernate里怎么实现呢?

一、绑定参数法:

Sql代码 复制代码 收藏代码
  1. Session session=HibernateUtil.getSessionFactory
  2. ().getCurrentSession();

  3. session.beginTransaction();

  4. String strSQL="from Classes as a where a.classno like :name";

  5. Query query = session.createQuery(strSQL);

  6. query.setString("name", "%"+OId+"%");

  7. List result=query.list();
  1. Session session=HibernateUtil.getSessionFactory  
  2. ().getCurrentSession();   
  3.   
  4. session.beginTransaction();  
  5.   
  6. String strSQL="from Classes as a where a.classno like :name";  
  7.   
  8. Query query = session.createQuery(strSQL);  
  9.          
  10. query.setString("name""%"+OId+"%");  
  11.          
  12. List result=query.list();  


二、在面向对象的查询语言 HQL

Sql代码 复制代码 收藏代码
  1. Session session = HibernateUtil.getSessionFactory().getCurrentSession();

  2. session.beginTransaction();

  3. List result=session.createQuery("from Classesas a where a.classno

  4. like " '%"+OId+"%'").list();
  1. Session session = HibernateUtil.getSessionFactory().getCurrentSession();   
  2.      
  3. session.beginTransaction();  
  4.   
  5. List result=session.createQuery("from Classes as a where a.classno   
  6.   
  7. like " '%"+OId+"%'").list();  

三、模糊查询参数化

Sql代码 复制代码 收藏代码
  1. Session session=HibernateUtil.getSessionFactory().getCurrentSession();

  2. session.beginTransaction();

  3. List result=session.createQuery("from Classesas a where a.classno

  4. like :name").setParameter("pid",OId).list();
  1. Session session=HibernateUtil.getSessionFactory().getCurrentSession();  
  2.   
  3. session.beginTransaction();  
  4.   
  5. List result=session.createQuery("from Classes as a where a.classno    
  6.   
  7. like :name").setParameter("pid",OId).list();  

Hibernate模糊查询参数化的问题

from Project o where 1=1 and o.isDeleted=? and o.prjName like ?; query.setString(i, "%"+实际查询条件+"%"); 注意参数中第一个百分号的左边与第二个百分号的右边都没有单引号,这和平时写SQL语句是不同的,要特别关注一下。另外还应该了解一下俩点的区别

HQL:from Project o where 1=1 and PRJ_NAME like '%strCond%';//这里PRJ_NAME 应该是数据库表中的实际字段名

HQL:from Project o where 1=1 and o.PRJ_NAME like '%strCond%';//这里PRJ_NAME 应该是实体类的属性名

HQL:from Project o where 1=1 and PRJ_NAME like '?';//这里的?不视为占位参数HQL:from Project o where 1=1 and PRJ_NAME like ?;//设置参数值时会自动在参数值两边加上单引号。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值