简体   繁体   中英

Running a nativeQuery in a loop doesn't return correct data

I am trying to run native query in a loop, the query displays the correct sql syntax but the output is always the same.

    for (int i=0; i<translations.size(); i++) {
        Query query = entityManager.createNativeQuery("Select * from " + translations.get(i).getName(), MyModel.class);
        rows = (List<MyModel>)query.getResultList();
        // rest of the function...
    }

now in the console I can see the Hibernate statements like:

Hibernate: Select * from translation1
Hibernate: Select * from translation2
Hibernate: Select * from translation3

but the variable "rows" always contains the result of the first select statement ie rows of translation1 table.

Any ideas why in the console it shows that it is selecting from other tables too but in reality it always gets data from translation1 table?

If all tables have the same set of ids, it's an expected behaviour.

Hibernate session cache guarantees that there can be only one instance of an entity of a particular type with a particular id inside a session. Since entities are resolved via the session cache even in the case of a native query, you get the same instances.

So, you have several options:

  • rethink your database shema
  • construct objects from query result manually
  • forcibly clear the session cache by calling clear() or detach()

Are you sure that the rows variable doesn't actually contain the LAST of your returned results? how do you initialize rows and what do you do with the variable inside the loop? If you want to get all the results from all the queries you have to add each one (inside the loop) to a list/set variable declared BEFORE the loop starts.

Or you could use some proper SQL and do:

SELECT * FROM Table1 [JOIN/UNION] Table2 etc...

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