简体   繁体   中英

iterating result in list object returned by hibernate query

I have hibernate query as below:

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();

Table myTable and myTable1 are entity classes.

myTO is a simple java class with properties col1, col2, col3, col4, col5.

The result of above query should be mapped to the properties of myTO.

How do I iterate the columns in result ? Or am I retrieving the result incorrectly ?

It seems you're trying to query a subset of the table's columns. For this you can use this example from 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];
     ....
}

If you don't have a problem to retrieve the whole entity (or at least its first level simple properties) you can just use:

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

Do you use any mapping for myTable? If it is mapped to type T then you can use this:

List<MyType> list = (List<MyType>)myQuery.getResultList();
list.get(0).getProperty1();

when field "property1" in MyTyoe is mapped to col1, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM