Iterate over the result in a list object returned by a sleep request

I have a sleep request, as shown 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(); 

The table myTable and myTable1 are entity classes.

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

The result of the above query should be matched with the properties of myTO.

How to iterate columns as a result? Or am I getting the result wrong?

+6
source share
2 answers

It seems you are trying to query a subset of table columns. For this, you can use this example from the Hibernate documentation :

11.4.1.2. Tuple Return Queries

Hibernation requests 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 have no problem retrieving the entire object (or at least its simple simple properties), you can simply use:

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

Do you use any mapping for myTable? If it maps to type T, you can use this:

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

when the field "property1" in MyTyoe is displayed, for example, on col1.

0
source

Source: https://habr.com/ru/post/901488/


All Articles