HQL
来源:互联网 发布:java培训贷款骗局流程 编辑:程序博客网 时间:2024/06/07 09:59
HQL————-Hibernate Query Language
HQL语言具有很高的兼容性
工具类HibernateSessionFactory:
package com.yyy.db;import org.hibernate.Session;import org.hibernate.cfg.Configuration;public class HibernateSessionFactory { private static String source = "\\hibernate.cfg.xml"; private static Configuration config; private static org.hibernate.SessionFactory sf; private static Session session; static { config = new Configuration().configure(source); sf = config.buildSessionFactory(); } public static Session getSession() { session = sf.openSession(); return session; } public static void closeSession(Session s) { s.close(); } public static void chengeSource(String s) { source = s; }}
使用hql语言的四个步骤:
1.得到session
session = HibernateSessionFactory.getSession();
2.编写HQL语言
String hql="from userInfo";
3.创建query
Query query =session.createQuery(hql);
4.执行查询
List list =query.list();
HQL 语句:
String hql="from UserInfo"; //这个UserInfo不是数据库中的表名,而是类名 //当查询整张表时,可以省略from前边的语句
模糊查询 like %xxxx%
String hql ="from UserInfo u where u.userName like %张三%"
用?协助查询
String hql="from UserInfo u where u.userName like ? and u.userId>?";Query query =session.createQuery(hql);query.setSting(0,"张三");query.setInteger(1,10);
用命名对象协助查询
String hql="from UserInfo u where u.userName like :m1 and u.userId>:m2";Query query =session.createQuery(hql);query.setSting("m1","张三"); //可以跟常量query.setInteger("m2",m2); //也可以跟变量
多表联合查询
String hql="from UserInfo u ,ClassInfo c where u.userId= c.userName;
返回的是一个二位数组
from之后的 表名 ,第几个表, 就是在二位数组中外围数组的下标
子查询
String hql="select userName from UserInfo u where u.userId in(select c.userId from ClassInfo c);
嵌套子查询返回一个一维数组
Query的分页查询:
public list serach(int pageNow,int pageSize){ query.setFirstResult((pageNow-1)*pageSize); query.setMaxResult(pageSize); list =query.list();}
注意:
在执行非select操作的时候 要在hibernate.cfg.xml中 加入:
<property name="hibernate.query.factory.class"> org.hibernate.hql.ast.AstQueryTranslatorFactory</property>
0 0