Hibernate查询多个表里的字段时,会返回Object类型的数据。
以mysql为例,以下为实现方法
public List<Topic> selectTopicById(int id) {
// TODO Auto-generated method stub
String hql="select t.tid,t.tuid,t.tsid,t.ttop,t.tdesc,t.ttime,t.tbg,u.uname,u.usex,u.udesc,u.uhead " +
"from Topic t,User u where t.tuid=u.uid and t.tid="+id;
List<Topic> list=new ArrayList<Topic>();
Topic t=new Topic();
List<Object[]> list1=this.getHibernateTemplate().find(hql);
for (Object o[] : list1) {
t.setTid((Integer)o[0]);
t.setTuid((Integer)o[1]);
t.setTsid((Integer)o[2]);
t.setTtop((String)o[3]);
t.setTdesc((String)o[4]);
t.setTtime((Date)o[5]);
t.setTbg((String)o[6]);
t.setUname((String)o[7]);
t.setUsex((String)o[8]);
t.setUdesc((String)o[9]);
t.setUhead((String)o[10]);
}
list.add(t);
return list;
}
感觉多有繁琐,因为我用的是getHibernateTemplate().find(hql);
下面这个感觉也可以,方法不同,先做个笔记咯。
private EntityManager em;
public void testJpaNativeQuery() {
String sql = "select t.class_no classNo ,t.student_no studentNo ,t.remark remark from t_student t where t.class_no like '%'||:class_no||'%' ";
// 执行查询 并把结果专为实体类
Query query = em.createNativeQuery(sql, Student.class);
// 获取查询结果
List<Student> students = query.getResultList();
}
附上我美美的鬼刀~