大家知道,在Hibernate Framework中,提供了三种查询数据的方式:
1.Hibernate Query Language (HQL):
它是ANSI SQL的最小OO Dialect,例:
session.createQuery("from Category c where c.name like 'Laptop%'");
entityManager.createQuery("select c from Category c where c.name like 'Laptop%'"); |
2.Criteria query :
它是HQL查询的延伸,提供了一些高级查询功能例:
session.createCriteria(Category.class)
.add( Restrictions.like("name", "Laptop%") ); |
3.Native SQL query :
session.createSQLQuery(
"select {c.*} from CATEGORY {c} where NAME like 'Laptop%'"
).addEntity("c", Category.class); |
最近,我在项目中经常遇到Hibernate数据查询的任务,我对一些我遇到的较难的课题举例进行说明:
《表述SELECT》
Criteria crit = session.createCriteria(User.class)
.setProjection( Projections.projectionList()
.add( Projections.property("lastname"))
.add( Projections.property("firstname"))
.list(); |
《表述WHERE》
Criteria crit = session.createCriteria(User.class)
.add(Restrictions.eq("email", "foo@hibernate.org"))
.uniqueResult(); |
《表述GROUP》
Criteria crit = session.createCriteria(User.class)
.setProjection( Projections.projectionList()
.add( Projections.groupProperty("lastname"))
.add( Projections.groupProperty("firstname"))
.list() |
《表述ORDER》
Criteria crit = session.createCriteria(User.class)
.addOrder( Order.asc("lastname") )
.addOrder( Order.asc("firstname") )
.list(); |
《取TOP 5结果》:
Criteria crit = session.createCriteria(Cat.class);
.setMaxResults(5)
.list(); |
《分页》:
Criteria crit = session.createCriteria(Cat.class)
.setFirstResult(1)
.setMaxResults(50)
.list(); |
《取查询结果》:
如果使用select或group,必须使用object[]来获得查询结果List值;
如果未使用select或group,必须使用java object[]来获得查询结果List值; |
《涉及组合primary key属性》:
Criteria crit = session.createCriteria(activitylog.class)
.add( Restricts.eq(“comp_id.custId”,customerid0) )
.add( Restricts.ge(“createdTs”, starttime) )
.add( Restricts.le(“createdTs”, endtime ) )
.list(); |
《Foreign Key联合查询》:
Criteria crit = session.createCriteria(activitylog.class)
.createAlias( “taskCodeRf”, “tc” )
.setProjection( Projections.projectionList()
.add( Projections.property("UserId"))
.add( Projections.property("tc.taskdescription"))
.list(); |
《Native Query》:
SQLQuery query = session.createSQLQuery(“select activitylog_seq.nextval as sessid from dual”);
Query.addScalar(“sessid”,Hibernate.LONG);
Long long0 = query.uniqueResult(); |
来源:http://www.99java.com/article/34/200812/200812171145.html