3

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 {


}
7
  • This link might be helpful to you - stackoverflow.com/questions/6170527/… Commented Jan 4, 2013 at 7:05
  • yes i have seen this .. i have already added <property name="packagesToScan" value="com.project.entities"/> to the entity manager bean which will scan all the entity classes .. Commented Jan 4, 2013 at 7:07
  • Try this one - forum.springsource.org/… Commented Jan 4, 2013 at 7:08
  • iss it required to add hibernate-annotation jar to the lib folder?? Commented Jan 4, 2013 at 7:14
  • hibernate 4.1.5 comes with inbuilt hibernate-annotations so it is not required Commented Jan 9, 2013 at 2:59

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

1 Comment

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
1

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

1 Comment

it is nt a proper entity file. I have placed this in db package and i am also using component scan for it
1

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");
 }

1 Comment

Name is correct only. Persistent unit provider is org.hibernate.ejb.HibernatePersistence and how to check if my persistence provider is properly registerd ?
0

Adding the annotation scanning in the persistence.xml solved the issue for me

<property name="hibernate.archive.autodetection" value="class, hbm" />

Even i tried giving the package scan in my entity manager like below also didnt work

  @Bean
       public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
           LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
           em.setDataSource(getDataSource());
           //em.setPackagesToScan("com.comp.proj.domain");
           em.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
           em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
           return em;
       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.