查询hibernate 部分数据

hibernate查出来人部分数据基本上是数组,有的时候需要对象(但是该对象只包含一部分数据,只需要这一部分)

1.Query q = session.createQuery("select new User(name,pwd) from User");

list=q.list();

  tran.commit();

2.Query query = getSessionFactory().getCurrentSession().createSQLQuery(hql).addScalar("title",Hibernate.STRING).setResultTransformer(Transformers.aliasToBean(Article.class)); //要转换成的po

   List list = session.createSQLQuery(hql.toString())   

            .addScalar("ID", Hibernate.LONG)//这里ID要用大写才对,不然会报列名错误   

            .addScalar("MT_NAME", Hibernate.STRING)//    

            .addScalar("MT_CODE", Hibernate.STRING)   

            .addScalar("NUM", Hibernate.DOUBLE)   

            .addScalar("MONEY", Hibernate.DOUBLE)//同上,都要大写   

            .list();        

3.Today I put an end to this jealousy and introduced ResultTransformer for HQL and SQL in Hibernate 3.2. 

List resultWithAliasedBean = s.createQuery(
  "select e.student.name as studentName," +
  "       e.course.description as courseDescription" +
  "from   Enrolment as e")
  .setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
  .list();

StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0);

   

相关推荐