实际应用中,我们查询的结果有时候会需要其他的类或者是一个新的包装类,即希望映射到一个DTO(即使hibernate早在很久就不推荐使用。。)但我还是说一下吧
如 我有这样子的两个类
//get和set方法均省略
public class Forum implements Serializable{ /** * */ private static final long serialVersionUID = 1L; //主键生成 用uuid private String forum_id; private String forum_title; private String forum_header; private String forum_description; private Date create_time; private Institution institution; //get set方法省略 }
public class Institution implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Integer institution_id; private String institution_name; private String description; private String image; private Date last_edittime; private boolean state; //get set 方法省略 }
我现在希望使用hibernate的sql语句查询出一些指定的字段,然后封装到一个实体中 ,由于查询出来的结果可能是个List 也可能是单个结果。所以这里推荐用List<object>类型来封装
希望查询出来字段都封装到下面这个类中
public class SendPojo implements Serializable{ /** * */ private static final long serialVersionUID = -5356294118259551164L; private String forum_id; private String forum_title; private String forum_header; private String forum_description; private Integer institution_id; //get set方法省略 }
那么可以在dao层这样子做
这里为方便演示只查询少数几个字段,实际上你可以查询多个,但是需要注意的是 在你的hql语句中查询结果名字 必须 和你设置的希望映射的实体属性名一样
String hql="select "f.forum_id,f.forum_title,i.institution_id from Forum f,Institution i where i.institution_id=1;
Query query = session.createQuery(hql);
Query query2 = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) ;
List list = query2.list();
return list;
可能有点不明确完整的可以参照这样
public List<PageForum> getForumList(final Integer currentPage, final Integer pageSize) { return getHibernateTemplate().execute(new HibernateCallback<List<PageForum>>() { @Override public List<PageForum> doInHibernate(Session session) throws HibernateException { String hql="select u.user_id as userId, f.forum_id as forumId , f.forum_title as forumTitle,f.forum_header as forumHeader,f.forum_description as forumDescription,f.create_time as createTime,i.image as image,i.institution_name as institutionName,u.username as authorName from Forum f,Institution i,User u where f.author.user_id=u.user_id and f.institution.institution_id=i.institution_id order by f.create_time desc"; Query query = session.createQuery(hql); query.setFirstResult((currentPage-1)*pageSize); query.setMaxResults(pageSize); Query query2 = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) ; List list = query2.list(); System.out.println(list.size()); return list; } }); }
其中ForumPage是我另外添加的DTO在应用中你可以按需求自己设定,但是如果没有必要并不推荐,因为这样是的要封装的属性很多,很浪费。