我有hibernate查询如下:
String MysqL = "SELECT S.col1,S.col2,T.col3,T.col4,T.col5 FROM myTable S,myTable1 T WHERE S.id = :id and S.id = T.id"; Query myQuery = this.em.createQuery(MysqL); myQuery.setParameter("id","123"); List<Object> result = myQuery.getResultList();
表myTable和myTable1是实体类.
myTO是一个简单的java类,其属性为col1,col2,col3,col4,col5.
如何迭代结果中的列?或者我是否错误地检索结果?
解决方法
您似乎正在尝试查询表的列的子集.为此,您可以使用Hibernate
documentation中的此示例:
11.4.1.2. Queries that return tuples
Hibernate queries sometimes return tuples of objects. Each tuple is returned as an array:
Iterator kittensAndMothers = sess.createQuery( "select kitten,mother from Cat kitten join kitten.mother mother") .list() .iterator(); while ( kittensAndMothers.hasNext() ) { Object[] tuple = (Object[]) kittensAndMothers.next(); Cat kitten = (Cat) tuple[0]; Cat mother = (Cat) tuple[1]; .... }
如果您没有问题来检索整个实体(或至少它的第一级简单属性),您可以使用:
List<Cat> cats = session.createQuery( "from Cat where cat.name = ?") .setString(0,name) .list(); for ( Cat cat : cats ) { Cat mother = cat.getMother(); ... }