java 使用 Spring 框架获取“未找到命名查询”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3154026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting 'Named query not found' with Spring framework
提问by Felipe Arenales
I have a Java class (Entity) with a set of named queries. When the Spring tries to inject the related bean, it is not finding one of the queries.
我有一个带有一组命名查询的 Java 类(实体)。当 Spring 尝试注入相关 bean 时,它没有找到查询之一。
As example:
例如:
@NamedQueries({
@NamedQuery(name = "Query1", query = "..."),
@NamedQuery(name = "Query2", query = "..."),
@NamedQuery(name = "Query3", query = "..."),
@NamedQuery(name = "Query4", query = "..."),
@NamedQuery(name = "Query5", query = "...")
})
When Spring tries to inject the bean, I′m getting:
当 Spring 尝试注入 bean 时,我得到:
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'myBean': Injection of resource methods failed;nested exception is
java.lang.IllegalArgumentException: Named query not found: Query3 at ...
I′m sure the queries are correct (all the unit tests for them are passing).
我确定查询是正确的(它们的所有单元测试都通过了)。
Does anybody know the root cause for it?
有人知道它的根本原因吗?
采纳答案by Felipe Arenales
Well, I′ve got the error. What was happening is as follows:
好吧,我有错误。发生的事情如下:
In my class there was one method annotated with @Resource, which called the named query declared in another class annotated with @Entity).
在我的班级中有一个用@Resource 注释的方法,它调用在另一个用@Entity 注释的类中声明的命名查询)。
So, when Spring injects and runs the method, it tries to use the named query. However, the query is not 'ready' to be used, and the exception throwed is that the query was not found.
因此,当 Spring 注入并运行该方法时,它会尝试使用命名查询。但是,该查询尚未“准备好”使用,并且抛出的异常是未找到该查询。
To solve this, I have to run a different method called when the Spring injections are finished, i.e., my class has to implement the interface org.springframework.context.ApplicationListener and the method onApplicationEvent waits for a org.springframework.context.event.ContextRefreshedEvent event.
为了解决这个问题,我必须在 Spring 注入完成时运行一个不同的方法,即,我的类必须实现接口 org.springframework.context.ApplicationListener 和方法 onApplicationEvent 等待 org.springframework.context.event。 ContextRefreshedEvent 事件。
That′s all guys. Thank you Bozho for your help.
这就是所有的家伙。感谢博卓的帮助。
回答by Bozho
make sure your entity has been mapped / scanned. Is it annotated with
@Entity, is it added to thepersistence.xmlor to the relevant provider configuration, or is it automatically scanned.I'd prefix the name of the class to the query - i.e.
MyEntity.Query1,MyEntity.Query1etc.verify whether there aren't deployment errors - i.e. that your query is correct
确保您的实体已被映射/扫描。它是用 注释的
@Entity,是添加到persistence.xml或 到相关的提供程序配置中,还是自动扫描的。我前缀类的名称来查询-即
MyEntity.Query1,MyEntity.Query1等等。验证是否没有部署错误 - 即您的查询是正确的

