Java – iterates the results in the list object returned by the hibernate query

I have hibernate query as follows:

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

Tables mytable and mytable1 are entity classes

Myto is a simple java class with attributes col1, col2, col3, col4, col5

The results of the above query should be mapped to the properties of myto

How do I iterate over the columns in the results? Or do I retrieve the results incorrectly?

Solution

It appears that you are trying to query a subset of the table's columns To do this, you can use this example in Hibernate documentation:

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 have no problem retrieving the entire entity (or at least its first level simple attributes), you can use:

List<Cat> cats = session.createQuery(
    "from Cat where cat.name = ?")
    .setString(0,name)
    .list();
for ( Cat cat : cats ) {
    Cat mother = cat.getMother();
    ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>