JPA查询可以将结果作为Java Map返回吗? [英] Can a JPA Query return results as a Java Map?
问题描述
我们当前正在基于命名的JPA查询返回的两个字段手动构建Map
,因为JPA 2.1仅提供了getResultList()
方法:
We are currently building a Map
manually based on the two fields that are returned by a named JPA query because JPA 2.1 only provides a getResultList()
method:
@NamedQuery{name="myQuery",query="select c.name, c.number from Client c"}
HashMap<Long,String> myMap = new HashMap<Long,String>();
for(Client c: em.createNamedQuery("myQuery").getResultList() ){
myMap.put(c.getNumber, c.getName);
}
但是,我觉得自定义映射器或类似的映射器会更有效,因为此列表可以轻松获得30,000多个结果.
But, I feel like a custom mapper or similar would be more performant since this list could easily be 30,000+ results.
任何无需手动迭代即可构建Map的想法.
Any ideas to build a Map without iterating manually.
(我正在使用OpenJPA,而不是休眠状态)
(I am using OpenJPA, not hibernate)
推荐答案
没有标准方法让JPA返回地图.
There is no standard way to get JPA to return a map.
请参阅相关问题: JPA 2.0本机查询结果作为地图
手动迭代应该没问题.相对于执行/返回查询结果的时间,在内存中迭代列表/映射的时间将很小.除非有确凿的证据表明手动迭代不可行,否则我不会尝试使用JPA内部或自定义功能.
Iterating manually should be fine. The time to iterate a list/map in memory is going to be small relative to the time to execute/return the query results. I wouldn't try to futz with the JPA internals or customization unless there was conclusive evidence that manual iteration was not workable.
此外,如果您在其他地方将查询结果列表转换为地图,则可能希望将其重构为带有参数的实用程序方法,以指示地图键属性.
Also, if you have other places where you turn query result Lists into Maps, you probably want to refactor that into a utility method with a parameter to indicate the map key property.
这篇关于JPA查询可以将结果作为Java Map返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!