Hibernate实现模糊查询的方法

一、绑定参数法:


Session session=HibernateUtil.getSessionFactory
().getCurrentSession();
session.beginTransaction();
String strSQL="from Classes as a where a.classno like :name";
Query query = session.createQuery(strSQL);
query.setString("name", "%"+OId+"%");
List result=query.list();


Session session=HibernateUtil.getSessionFactory
().getCurrentSession();

session.beginTransaction();

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

Query query = session.createQuery(strSQL);

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

List result=query.list();


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


Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result=session.createQuery("from Classes as a where a.classno
like " '%"+OId+"%'").list();


Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

List result=session.createQuery("from Classes as a where a.classno

like " '%"+OId+"%'").list();

三、模糊查询参数化


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


Session session=HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

List result=session.createQuery("from Classes as a where a.classno

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 ?;//设置参数值时会自动在参数值两边加上单引号。

你可能感兴趣的:(hibernate)