QBC和QBE
Criteria是Criterion的复数,是"标准、准则、约束"的意思。
用法:
@Test public void testQBC() { Session session = sf.openSession(); session.beginTransaction(); //criterion 标准/准则/约束 Criteria c = session.createCriteria(Topic.class) //from Topic .add(Restrictions.gt("id", 2)) //greater than = id > 2 .add(Restrictions.lt("id", 8)) //little than = id < 8 .add(Restrictions.like("title", "t_")) .createCriteria("category") .add(Restrictions.between("id", 3, 5)) //category.id >= 3 and category.id <=5 ; //DetachedCriterea for(Object o : c.list()) { Topic t = (Topic)o; System.out.println(t.getId() + "-" + t.getTitle()); } session.getTransaction().commit(); session.close(); }
测试结果:
Hibernate:
select
this_.id as id2_1_,
this_.category_id as category4_2_1_,
this_.createDate as createDate2_1_,
this_.title as title2_1_,
category1_.id as id0_0_,
category1_.name as name0_0_
from
Topic this_
inner join
Category category1_
on this_.category_id=category1_.id
where
this_.id>?
and this_.id<?
and this_.title like ?
and category1_.id between ? and ?
QBE:(Query By Example)
QBE是QBC的一部分
//is empty and is not empty //query by criteria query by example @Test public void testQBE() { Session session = sf.openSession(); session.beginTransaction(); Topic tExample = new Topic(); tExample.setTitle("T_"); Example e = Example.create(tExample) .ignoreCase().enableLike(); Criteria c = session.createCriteria(Topic.class) .add(Restrictions.gt("id", 2)) .add(Restrictions.lt("id", 8)) .add(e) ; for(Object o : c.list()) { Topic t = (Topic)o; System.out.println(t.getId() + "-" + t.getTitle()); } session.getTransaction().commit(); session.close(); }
转载请注明出处:http://blog.csdn.net/acmman/article/details/43937517