HQL (一) 简单属性查询
简单属性查询(重要)
* 单一属性查询,返回结果集是属性列表,其元素类型和实体类中相应的属性类型一致
* 多个属性查询,返回的结果集是对象数组,数组的长度和查询的属性的个数一致
数组元素的类型和查询的属性类型一致
* 如果认为返回的数组不够对象化,可以采用hql动态生成实体对象
参加:SimplePropertyQueryTest.java
- package com.wlh.hibernate;
- import java.util.Iterator;
- import java.util.List;
- import junit.framework.TestCase;
- import org.hibernate.Session;
- public class SimplePropertyTest extends TestCase{
- //单个属性查询
- public void testQuery1(){
- Session session = null;
- try {
- session = HibernateUtils.getSession();
- session.beginTransaction();
- //单个属性查询,返回结果集属性集合,其元素类型和实体类中相应属性的类型一致
- List students=session.createQuery("select name from Student ").list();
- for(Iterator iter=students.iterator();iter.hasNext();){
- String name=(String)iter.next();
- System.out.println("name="+name);
- }
- session.getTransaction().commit();
- }catch(Exception e) {
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally {
- HibernateUtils.closeSession(session);
- }
- }
- //多个属性查询
- public void testQuery2(){
- Session session = null;
- try {
- session = HibernateUtils.getSession();
- session.beginTransaction();
- //查询多个属性其集合元素是对象数组l列表。即,多个对象数组的集合
- //数组元素中的类型与对应的实体类中的属性类型一致
- //数组的长度取决于查询的属性个数
- List students=session.createQuery("select id,name from Student ").list();
- for(Iterator iter=students.iterator();iter.hasNext();){
- Object[] o=(Object [])iter.next();
- System.out.println("id="+o[0]+",name="+o[1]);
- }
- session.getTransaction().commit();
- }catch(Exception e) {
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally {
- HibernateUtils.closeSession(session);
- }
- }
- //多个属性查询
- public void testQuery3(){
- Session session = null;
- try {
- session = HibernateUtils.getSession();
- session.beginTransaction();
- List students=session.createQuery("select new Student(id,name) from Student ").list();
- for(Iterator iter=students.iterator();iter.hasNext();){
- Student o=(Student)iter.next();
- System.out.println("id="+o.getId()+",name="+o.getName());
- }
- session.getTransaction().commit();
- }catch(Exception e) {
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally {
- HibernateUtils.closeSession(session);
- }
- }
- }