+++在映射文件中定义命名查询
<class .. >
</class>
<query name="findCustomersByName"><![CDATA[
from Customer c where c.name like :name
]]></query>
语句:Query q=session.getNamedQuery("findCustomersByName");
q.setString("name",name);
List result=query.list();
++++ HQL Vs QBC 检索方式
比较运算
1 . 检索年龄大于18的Customer
HQL session.createQuery("from Customer cwhere c.age>18");
QBC Criteria criteria=session.createCriteria(Customer.class);
criteria.add(Expression.gt("age",18));
2 . 检索年龄不等于 18的
HQL session.createQuery("from Customer c where c.age<>18")
QBC Criteria criteria =session.createCriteria(Customer.class);
criteria.add(Expression.not(Expression.eq("age",new Integer(18))));
3. 检索姓名为空的Customer对象
HQL session.createQuery("from Customer c where c.name is null");
QBC Criteria criteria =session.createCriteria(Customer.class);
criteria.add(Expression.isNull("name"));
4. 检索不属于任何客户的订单
HQL session.createQuery("from Order o where o.customer is null");
QBC Criteria criteria =session.createCriteria(Order.class);
criteria.add(Expression.isNull("customer"));
5. HQL Query q=session.createQuery("from Customer c where lower(c.name)='tom'");
Query q=session.createQuery("from Customer c where upper(c.name)='TOM'");
QBC Criteria criteria =session.createCriteria(Customer.class);
criteria.add(Expression.eq("name","tom").ignoreCase());
范围运算
1. 检查姓名为 Tom,Mike 或者Jack 的 Customer对象
HQL session.createQuery("from Customer c where c.name in('Tom','Mike','Jack')");
QBC Criteria criteria=session.createCriteria(Customer.class);
String names[]={"Tom","Mike","Jack"};
criteria.add(Expression.in("name",names));
2. 检查年龄在 18 到 25之间的Customer对象
HQL session.createQuery("from Customer c where c.age between 18 and 25");
QBC Criteria criteria=session.createCriteria(Customer.class);
criteria.add(Expression.between("age",new Integer(18),newInteger(25)))
3. 检索年龄不在 18到 25之间的Customer对象;
HQL session.createQuery("from Customer c where c.age not between 18 and 25");
QBC Criteria criteria=session.createCriteria(Customer.class);
criteria.add(Expression.not(Expression.between("age",new Integer(18),newInteger(25))))
字符串模式匹配
1. 检索姓名以 "T"开头的Customer对象
HQL session.createQuery("from Customer cwhere c.name like 'T%'");
QBC Criteria criteria=session.createCriteria(Customer.class);
criteria.add(Expression.like("name","T%"));
%表示 任意个字符
_表示 一个字符
Or
criteria.add(Expression.like("name","T",MatchMode.START));
MatchMode 类中有:
START