在循环中运行nativeQuery不会返回正确的数据
我试图在循环中运行本机查询,查询显示正确的 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...
}
现在在控制台中我可以看到 Hibernate 语句,如下所示:
Hibernate: Select * from translation1
Hibernate: Select * from translation2
Hibernate: Select * from translation3
但变量“rows”始终包含第一个 select 语句的结果,即 Translation1 表的行。
有什么想法为什么在控制台中它显示它也在从其他表中进行选择,但实际上它总是从 Translation1 表中获取数据?
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 i.e. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果所有表都有相同的 id 集,则这是预期的行为。
Hibernate 会话缓存保证会话中只能存在具有特定 id 的特定类型实体的一个实例。由于即使在本机查询的情况下实体也是通过会话缓存解析的,因此您会获得相同的实例。
因此,您有多种选择:
clear()
或detach()
手动强制清除会话缓存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:
clear()
ordetach()
您确定 rows 变量实际上不包含返回结果的最后一个吗?如何初始化行以及如何处理循环内的变量?如果您想获取所有查询的所有结果,则必须将每个查询(在循环内)添加到循环开始之前声明的列表/集合变量中。
或者你可以使用一些适当的 SQL 并执行以下操作:
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: