简体   繁体   English

在循环中运行nativeQuery不会返回正确的数据

[英]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. 我试图在循环中运行本机查询,查询显示正确的SQL语法,但输出始终相同。

    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语句如:

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. 但变量“rows”总是包含第一个select语句的结果,即translation1表的行。

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? 任何想法为什么在控制台中它显示它也从其他表中选择但实际上它总是从translation1表获取数据?

If all tables have the same set of ids, it's an expected behaviour. 如果所有表都具有相同的id组,则它是预期的行为。

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. Hibernate会话高速缓存保证在会话中只有一个特定类型的实体的实例具有特定的id。 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() 通过调用clear()detach()强制清除会话缓存

Are you sure that the rows variable doesn't actually contain the LAST of your returned results? 你确定rows变量实际上不包含返回结果的最后一行吗? 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: 或者您可以使用一些正确的SQL并执行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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