views:

59

answers:

2

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.

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:

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?

A: 
  • make sure your entity has been mapped / scanned. Is it annotated with @Entity, is it added to the persistence.xml or 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.Query1 etc.

  • verify whether there aren't deployment errors - i.e. that your query is correct

Bozho
Bozho: 1)Yes, my entity is annotated with @Entity. The main point is that only ONE query is not being found. All the others are. 2)In my real project, I name my query as constants, such as QUERY1. So, when I call one query in another class, it´s in the form: MyEntity.QUERY1. So, I still have no solution for my problem. Thank you anyway.
check my third point.
Bozho
Your third point is answered in my edited question description. Thank you one more time.
+1  A: 

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).

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.

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.

That´s all guys. Thank you Bozho for your help.