介绍和基本语法
HQL大小写不敏感,当有相同的实体类名时,使用包名.实体类
Queryquery=session.createQuery("fromCatc");
List<Cat>catlist=query.list();返
回单个对象Queryq=session.createQuery("selectcount(c)fromCatc");
Numbernum=(Number)q.uniqueResult();//返回单个实例
intcount=num.intValue();//返回数值
查询总数时,HQL格式必须为以上语句格式,返回值可能为
ShortIntegerLongBigInteger具体由主键的类型而定
返回Object[]数组L
ist<Object[]>list=session.createQuery
("selectc.name,c.motherfromCatc").list();
//获取
for(Object[]row:list){
for(Objectobj:row){
System.out.println(obj);
}
}返
回List类型Stringhql="selectnewList(c.name,c.mother)fromCatc"'
List<List>list=session.cresteQuery(hql).list();
//获取
For(Listrow:list){
For(Objectobj:row){
System.out.println(obj);
}
}返
回Map类型Stringhql="sesectnewmap(c.nameasname,c.motherasmother)"+"fromCatc";
ListlistMap=session.creatgQuery(hql).list();
//获取
for(Mapmap:(List<Map>listMap){
System.out.println("Name:"+map.get("name"));
System.out.println("Mother:"+map.get("mother"));
}返回实体对象Stringhql="selectnewCat(cat.name,cat.createDate)fromCatc";
List<Cat>catList=session.createQuery(hql).list();
注意:
这样使用时,Cat类中必须存在一个publicCat(Stringname,DatecreateDate)
的构造方法。因为Hibernate是通过调用该构造方法完成返回值从Object[]数组
转化到Cat类实体类的。条
件查询和运算符Where子句的语法
Stringhql="selectcfromCatc"+"wherec.mother.name=null
andc.createDate<:createDate";
session.createQuery(hql).setParameter("createDate",newDate()).list();
表达式setParameter()传递参数H
QL支持的运算符?数学运算符:+-*/
?比较操作符:=!=<<=>>=like
?逻辑计算法:andornot
?SQL操作符:in、notin、between、isnull、isnotnull
isempty、numberof
?字符串连接:||或concat("","")
?时间日期函数:current_date()current_time()current_timestamp()
Second()minute()hour()day()month()year()
?JPA定义的操作:substring()coalesce()lower()upper()lenth()
Locate()abs()sqrt()bit_lenth()nullif()trim()
?数据库支持的SQL标量函数:sign()trunc()rtrim()sin()
?简单的跳转语句:case...when...then...else...end语
法:看高级查询,设置查询条件时,应尽量使用setParameter()传递参数。
统计函数S
tringhql="selectcount(c)fromCatcwherec.mother!=null";
Numbernum=(Number)session.createQuery(hql).uniqueResult();
intcount=num.intValue();//同返回单个对象H
QL分页显示Stringhql="selectcount(c)fromCatc";
Longcount=(Long)session.createQuery(hql).uniqueResult();//查询记录总数
List<Cat>ccList=session.createQuery("fromCat")
.setFirstResult(0)//从第0条开始
.setMaxResults(10).list();//取10条数据HQL连表查询Stringhql="selectefromEventewheree.cat.name='Ketty'";
List<Event>eventList=sessionQuery(hql).list();
Where子句用到了Car表
Stringhql="selectcfromCatcleftjoinc.eventse
wheree.descriptionlike:str";
List<Cat>list=session.createQuery(hql).setParameter("str","%dd%").list();使
用SQL数据库Hql为jdbc格式
Stringhql="select*fromtb_cat";
SQLQuerysqlquery=session.createSQLQuery(hql);
sqlquery.addEntity(Cat.class);//设置输出类型
List<Cat>catList=sqlquery.list();命
名常用的查询实体类中@注解配置,使用直接引用名字。
@NamedQuery(name="cat",query="selectcfromCatc")
@NamedNativeQuery(name="cat",query="select*fromtb_cat)
Hibernate中的Query一些基本用法
最新推荐文章于 2024-03-03 15:20:58 发布