hql查询对象、查询属性

    //查询整个对象集合
    public void testHqlFind(){
    	Configuration cfg = new Configuration().configure();
    	SessionFactory sessionFactory = cfg.buildSessionFactory();
    	Session session = sessionFactory.openSession();
    	Transaction ts = session.beginTransaction();
    	//注意下面hql是查询的整个实体集合
    	List persons = session.createQuery(
    			"from Person p where name like :myname")
    			.setString("myname", "lijuan%").list();
    	for(Iterator it = persons.iterator();it.hasNext();){
    		Person p = (Person)it.next();
    		System.out.println(p.getName() + "-" + p.getAge());
    	}
    	ts.commit();
    	session.flush();
    	sessionFactory.close();
    }
    
    //查询属性
    public void testHqlFindProperty(){
    	Configuration cfg = new Configuration().configure();
    	SessionFactory sessionFactory = cfg.buildSessionFactory();
    	Session session = sessionFactory.openSession();
    	Transaction ts = session.beginTransaction();
    	//注意查询属性的方式:使用 p.id  p.name  p.address
    	List persons = session.createQuery("select p.id,p.name,p.address from Person p where p.name like :myname ")
    			       .setString("myname", "%lijuan%").list();
    	for(Iterator it = persons.iterator(); it.hasNext();){
    		Object[] objs = (Object[])it.next();
    		System.out.println(java.util.Arrays.toString(objs));
    	}
    }

你可能感兴趣的:(hql查询对象、查询属性)