Posted on 2011-12-03 00:05
陈小东 阅读(673)
评论(0) 编辑 收藏
实体查询
例子1:
- String hql=”from User user ”;
- List list=session.CreateQuery(hql).list();
String hql=”from User user ”;
List list=session.CreateQuery(hql).list();
因为HQL语句与标准SQL语句相似,所以我们也可以在HQL语句中使用where字句,并且可以在where字句中使用各种表达式,比较操作符以及使用“and”,”or”连接不同的查询条件的组合。看下面的一些简单的例子:
- from User user where user.age=20;
from User user where user.age=20;
例子2(返回一个属性):
- String hql= "select c.customerNamefrom Customer c“;
- Query query= session.createQuery(hql);
- Iteratorit = query.list().iterator();
- System.out.println(query.list().size());
- while(it.hasNext()) {
- String c = (String)it.next();
- System.out.println(c);
- }
String hql= "select c.customerNamefrom Customer c“;
Query query= session.createQuery(hql);
Iteratorit = query.list().iterator();
System.out.println(query.list().size());
while(it.hasNext()) {
String c = (String)it.next();
System.out.println(c);
}
例子3(返回多个属性):
如果返回多个属性,那么它们将被装入数组或者集合中
- String hql= "select c.customerId, c.customerName“+
- “from Customer c“;
- Query query= session.createQuery(hql);
- Iteratorit = query.list().iterator();
- while(it.hasNext()) {
- Object[] obj= (Object[])it.next(); // List list= (List)it.next();
- Long id = (Long)obj[0]; //Long id = (Long)list.get(0);
- String name = (String)obj[1]; //String name = (String)list.get(1);
- System.out.println(id.longValue() + " " + name);
- }