5

Trying to learn Hibernate, i am trying to learn how to execute NamedQuries but evertime i am getting Exception in thread "main" org.hibernate.MappingException: Named query not known.Please help me out here

Error (only the message, not showing complete stack)

Exception in thread "main" org.hibernate.MappingException: Named query not known: hibernate_tut_emp.Employee.FindCountOfNames
    at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
    at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
    at hibernate_tut_emp.MyOps.main(MyOps.java:20)

Employee.java

package hibernate_tut_emp;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;



@Entity
@Table(name="Hib1")

@NamedQueries({
    @NamedQuery(name="GetDetailsByName" , query="select * from hib1 h where h.name=:name"),
    @NamedQuery(name="FindCountOfNames", query="select count(1) as cnt from hib1 h where h.name=:name")
})
public class Employee {
    private int id;
    private String name;

    @Id
    @Column(name="id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
            this.id = id;
    }

    @Column(name="name")
    public String getName() {
            return name;
    }

    public void setName(String empName) {
            this.name = empName;
    }


}

MyOps.java

package hibernate_tut_emp;

import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class MyOps {

    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        System.out.print("Enter a name : ");
        String name = scnr.next();

        SessionFactory ses = HibernateUtil.getSessionFactory();
        Session session = ses.openSession();

        Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");


        query.setString("name", name);
        int count = ((Integer)query.iterate().next()).intValue();
        System.out.println("count : "+count);
    }
}

employee.hbm.xml

<?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>
    <class name="hibernate_tut_emp.Employee" table="hib1">
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="name" type="string" column="name" />
    </class>
</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
         <property name="connection.username">root</property>
         <property name="connection.password">mayank</property>

        <!-- JDBC connection pool (use the built-in) -->
         <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
          <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
         <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
         <property name="hbm2ddl.auto">update</property>

      <mapping class="hibernate_tut_emp.Employee" />
      <mapping resource="employee.hbm.xml"/>

     </session-factory>
 </hibernate-configuration>

I googled out everything possible but i think i am overlooking some basic stuff.Any indication in right direction is appreciated! :)

One thing i considered is that if i have defined in class file NamedQueries, i do not need to mention it in xml file.Please correct me if i am wrong!

7
  • 2
    Why do you use both a class and its annotations, and an xml file, todefine the mapping of the same class? Just use one of them (the class and its annotations, preferrably). Also note that both of the queries are incorrect. * is SQL, not HQL. HQL uses entity names (i.e. class names), and not table names. And h isn't defined in the second query. Commented Sep 28, 2014 at 10:39
  • @JBNizet : ok...so you mean if i have annotations in Employee.java i do not need employee.hbm.xml? Commented Sep 28, 2014 at 10:41
  • No, you don't need it. XML mapping was useful when annotations didn't exist (Java 4, we're at Java 8). Commented Sep 28, 2014 at 10:42
  • 2
    I would hazard a guess that because you are mapping the file using employee.hbm.xml any and all annotations are unceremoniously ignored. You need to remove all hbm.xml files and their references. Then you should begin to get startup errors due to your HQL being invalid. Commented Sep 28, 2014 at 10:42
  • 2
    Yup, now you need to read the HQL documentation and write some valid queries. HQL != SQL! Maybe start with from Employee where name = :name. Commented Sep 28, 2014 at 10:47

1 Answer 1

5

There are several issues here:

  1. Your named queries should use entities not tables. If you want native queries you should use NamedNativeQuery instead.

  2. You don't need to supply the entity name when fetching the query.

    Change this:

    Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
    

    to:

    Query query = session.getNamedQuery("FindCountOfNames");
    
Sign up to request clarification or add additional context in comments.

5 Comments

one question though...when i get the SQL query printed it print some other names like Select employee_0_o ... like that but table is mapped as employee only...is this normal?
That's after table name and it's the Hibernate table aliasing. Nothing to worry about.
but its not fetching me the desired output...i am using the FindCountOfNames named query, but irrespective of what i set to the :name, i am getting 0 as output...any ideas?
I think it's better to ask a new question with the exact current mapping and code example. Ping me when you're done.
then i'll ping you after 2 days! :D

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.