Hibernate 查询结果转换为实体类型 (HQL_SQL)

在使用 Hibernate 时,大部分情况使用 HQL 直接得到的就是实体了,但有时你或许要用到自定义实体的转换,可以参考如下

1.POJO 实体

  session.createSQLQuery(queryString.toString()).addEntity(实体.class);

2. 普通JavaBean(非 HibernatePOJO 实体)

  SQLQuery query = session.createSQLQuery(“select vg189.gdname busiType,ob.tel busiNo,ob.order_number orderNo,ob.create_time ctime”);

  query.addScalar(“busiType”, Hibernate.STRING)

  .addScalar(“busiNo”, Hibernate.STRING)

  .addScalar(“orderNo”, Hibernate.STRING)

  .addScalar(“ctime”, Hibernate.STRING);

  query.setResultTransformer(Transformers.aliasToBean( 实体.class));

  return query.list();

  注:示例中 addScalar 及 setResultTransformer 很关键,我在使用的时候还报了一个错 (原因是在实体中需要有一个无参构造函数)

  org.springframework.orm.hibernate3.HibernateSystemException: Could not instantiate resultclass: com.yysoft.ecss.eshop.webservice.imp.model.OrderMd; nested exception is org.hibernate.HibernateException: Could not instantiate resultclass: com.yysoft.ecss.eshop.webservice.imp.model.OrderMd

  Caused by: org.hibernate.HibernateException: Could not instantiate resultclass: com.yysoft.ecss.eshop.webservice.imp.model.OrderMd

  at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:69)

  at org.hibernate.hql.HolderInstantiator.instantiate(HolderInstantiator.java:69)

3. 返回多个实体

  session.createSQLQuery(“SELECT {cat.}, {mother.} FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID”)

  .addEntity(“cat”, Cat.class)

  .addEntity(“mother”, Cat.class)

  {cat.*} 中的 cat,既为 addEntity 里面的 cat 名称。