迭代hibernate查询返回的列表对象中的结果

Vic*_*cky 7 java hibernate list

我有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();
Run Code Online (Sandbox Code Playgroud)

表myTable和myTable1是实体类.

myTO是一个简单的java类,其属性为col1,col2,col3,col4,col5.

上述查询的结果应该映射到myTO的属性.

如何迭代结果中的列?或者我是否错误地检索结果?

yai*_*air 16

您似乎正在尝试查询表的列的子集.为此,您可以使用Hibernate 文档中的此示例:

11.4.1.2.返回元组的查询

Hibernate查询有时会返回对象的元组.每个元组都以数组形式返回:

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];
     ....
}
Run Code Online (Sandbox Code Playgroud)

如果您没有问题来检索整个实体(或至少它的第一级简单属性),您可以使用:

List<Cat> cats = session.createQuery(
    "from Cat where cat.name = ?")
    .setString(0, name)
    .list();
for ( Cat cat : cats ) {
    Cat mother = cat.getMother();
    ...
}
Run Code Online (Sandbox Code Playgroud)