java.lang.IllegalArgumentException: Named query not found.(Entity Manager not creating NamedQuery)

25,670

Solution 1

I have written all named queries in a class with @NamedQuery annotation

You have not mentioned clearly the type of class that you are referring in the above statement? You would need to write named queries in Entity class (class annotated with @Entity annotation).

UPDATE: I am somewhat now confused about your class DBNamedQuery. You said you are using one class to put all named queries. My understanding is you are using this class to write named queries for all the entities of your application. If that is correct how can you use @Entity annotation on your class DBNamedQuery because it is not really a jpa entity?

A class that contains @NamedQuery annotation should be a managed entity. And I suspect your class DBNamedQuery is not.

To identify the problem I suggest check in the logs if that is a manged entity. If you cannot do that then EntityManger gives you and API to check that during runtime contains(java.lang.Object entity).

On a related note, if you are using annotation then for JPA Named Queries are part of jpa entity. Using xml gives you a flexibility to store in a separate file.

Solution 2

hi i got your problem instead of creating a class why not u create a xml file for named query like Queries.hbm.xml like as follow

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- Query For User TO -->
    <query name="loadUserByUsername">from User u where u.username = ?</query>
</hibernate-mapping>

keep this xml file in resources folder and in your applicationContext-enterprise-config.xml file write it as follow

<property name="mappingResources">
    <list>
        <value>/resources/hbms/Queries.hbm.xml</value>
    </list>
</property>

so it will work fine.

Edit Well It's Depends how You Call it in your DAO Layer. You have to call like =>

public int executeNamedQuery(String namedQuery, String namedParams[], Object params[]) throws DatabaseException {
        int result = 0;
        Session session = getSession();
        final String methodName = "executeNamedQuery";
        try {
            session.beginTransaction();
            Query q = session.getNamedQuery(namedQuery);
            if (namedParams != null) {
                for (int i = 0; i < namedParams.length; i++) {
                    q.setParameter(namedParams[i], params[i]);
                }
            }
            result = q.executeUpdate();
            session.getTransaction().commit();
            logger.debug("{} :: {} = {}", new Object[] { methodName, "No. of objects affected", result });
        } catch (HibernateException e) {
            session.getTransaction().rollback();

            final String message = "Couldn't execute the named query " + namedQuery;
            logger.error("{} :: {}", new Object[] { methodName, message, e });
            throw new DatabaseException(getClass(), methodName, message, e);
        } finally {
            closeSession();
        }
        return result;
    }

Note: 1) namedQuery means name of query in Queries.hbm.xml file. 2) namedParams[] means parameters name for Query. 3) params means value for parameters .

Solution 3

Check if your entity class DBNamedQuery is in the package com.project.entities as you configured in the ApplicationContext.xml file

Solution 4

I think it is because of name miss match. The name which is declare in @NamedQuery in not match with the name which is called that query.

e.g

@NamedQuery(name = "AAAA", query = ... ) //must be same the name which call that query

public void some() {
   Query q = em.createNamedQuery("AAAA");
 }
Share:
25,670
Kabilan S
Author by

Kabilan S

Updated on July 09, 2022

Comments

  • Kabilan S
    Kabilan S almost 2 years

    I am using hibernate 4.1.5.Final and Spring 3.1.2 Release and Jboss 7.1 . I have written all named queries in a class with @NamedQuery annotation but entity manager not creating named query . i am posting the stacktrace and context.xml

      09:58:49,695 ERROR [stderr] (http-localhost-127.0.0.1-8080-2) java.lang.IllegalArgumentException: Named query not found: validateLoginHash
        09:58:49,770 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:642)
        09:58:49,772 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
        09:58:49,774 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        09:58:49,777 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at java.lang.reflect.Method.invoke(Method.java:597)
        09:58:49,779 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    
        09:58:49,782 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at $Proxy30.createNamedQuery(Unknown Source)
    
        09:58:49,784 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
    
        09:58:49,785 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    
        09:58:49,788 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at java.lang.reflect.Method.invoke(Method.java:597)
    
        09:58:49,790 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    
        09:58:49,793 ERROR [stderr] (http-localhost-127.0.0.1-8080-2)   at $Proxy30.createNamedQuery(Unknown Source)
    

    ApplicationContext.xml

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/> 
        <bean id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    
    
            <property name="dataSource" ref="dataSource" />
            <property name="jpaDialect" ref="jpaDialect"/>
            <property name="packagesToScan" value="com.project.entities"/> 
    
    
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">          
                    <property name="showSql" value="false" />
                    <property name="generateDdl" value="false" />
                    <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                </bean>
            </property>
    
    <!--        <property name="persistenceUnitName" value="Project" /> -->
            <property name="persistenceXmlLocation" value="classpath:META-INF/jpa-persistence.xml"/> 
    
            <property name="loadTimeWeaver">
                <bean
                    class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
            </property>
    
        </bean>
    
         <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
            <property name="jndiName" value="java:jboss/datasources/MySqlDS"/>
        </bean>
    
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
            <property name="dataSource" ref="dataSource" />
        </bean>
    

    jpa-persistence.xml

    <persistence>
        <persistence-unit name="Project" transaction-type="RESOURCE_LOCAL" >
    
    
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
             <non-jta-data-source>java:jboss/datasources/MySqlDS</non-jta-data-source>
    <!--         <properties>  -->
    <!--           <property name="jboss.as.jpa.providerModule" value="hibernate3-bundled" />        -->
    <!--           </properties>          -->
    
        </persistence-unit>
    
    </persistence>
    

    DBNamedQuery.java

    @Entity
    @NamedQueries( {
    
    @NamedQuery(name = ... , query = ... ),
    @NamedQuery(name = ..., query = ...),
    
    .....More named queries
    
    })
    
    public class DBNamedQuery {
    
    
    }
    
  • Kabilan S
    Kabilan S over 11 years
    it is nt a proper entity file. I have placed this in db package and i am also using component scan for it
  • Kabilan S
    Kabilan S over 11 years
    yes ur right DBNamedQuery is nt a jpa entity i use it to write all my queries alone for all the entities. org.hibernate.ejb3persistence is my persistence provider . the error means my persistence unit not properly registerd ?
  • Kabilan S
    Kabilan S over 11 years
    Name is correct only. Persistent unit provider is org.hibernate.ejb.HibernatePersistence and how to check if my persistence provider is properly registerd ?
  • Prafulla
    Prafulla over 11 years
    See I have edited Answer You have to do like this, and you have to do entry of applicationContext-enterprise-config.xml file in web.xml also
  • Parvez
    Parvez over 11 years
    @Kabilan: I wouldn't say persistence unit is properly registered. The error means your named queries are not present where it should be because it looks named query only in Entities or xml registered with persistence unit. You can either move your named queries to respective entities or a separate xml and define that xml in persistence.xml so that persistence unit is aware of it.