2

This is my class to fetch data from database

package com.javatpoint.mypackage;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.List;

public class retrive {
    public static void main(String args[]) {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");// populates the data of the
                                            // configuration file

        // creating seession factory object
        SessionFactory factory = cfg.buildSessionFactory();

        // creating session object
        Session session = factory.openSession();

        // creating transaction object
        Transaction t = session.beginTransaction();

        Query query = session.createQuery("from EMPLOYEE");
        java.util.List list = query.list();
        System.out.println(list);
        t.commit();
        session.close();
    }
}

This is my Emplouyee.hbm.xml file :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 5 Dec, 2013 12:09:18 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping default-lazy="false">
    <class name="com.javatpoint.mypackage.Employee" table="EMPLOYEE">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property generated="never" lazy="false" name="firstName"
            type="java.lang.String">
            <column name="FIRSTNAME" />
        </property>
        <property generated="never" lazy="false" name="lastName"
            type="java.lang.String">
            <column name="LASTNAME" />
        </property>
    </class>
</hibernate-mapping>

when i run this Program then following Exception come please help me how to Fix it i am new in Hibernate and trying learn but am stuck.

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: 
           EMPLOYEE is not mapped [from EMPLOYEE]

while i am able to store data in database i have 2 class one for String data and second fetching data Problem is coming in fetching data plz help.

1
  • you can find answer on beginner level tutorials itself Commented Dec 26, 2013 at 9:48

6 Answers 6

9

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

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

2 Comments

its correct But i am getting Output in this format :Hibernate: select employee0_.ID as ID0_, employee0_.FIRSTNAME as FIRSTNAME0_, employee0_.LASTNAME as LASTNAME0_ from EMPLOYEE employee0_ [com.javatpoint.mypackage.Employee@181ed9e, com.javatpoint.mypackage.Employee@bc8e1e, com.javatpoint.mypackage.Employee@11671b2, com.javatpoint.mypackage.Employee@82764b, com.javatpoint.mypackage.Employee@1bf3d87] while i want to get the table value please help how i will do this
I dont really know what your problem is right now - try it via the hibernate criteria API suggested from hd1. That way you should be able to know how to handle the result. List<Employee> employees = (List<Employee>) session.createCriteria(Employee.class).list()
6

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

5 Comments

HibernateUtil what is this am not able to find such constructor?
@dmitry.sh Why do we need transaction and roll back for reading data from table?
@dmitry.sh What i meant is "for reading operation, why do we need a transaction with commit and rollback?". What it is going to commit/rollback?
@dmitry.sh Thanks for the pointers! Now i know the difference :)
2

try the class-name

Query query = session.createQuery("from Employee");

instead of the table name

Query query = session.createQuery("from EMPLOYEE");

2 Comments

No, the better way is to use the Hibernate Criteria API, your query will then become: List<Employee> employees = (List<Employee>) session.createCriteria(Employee.class).list()
@hd1 Criteria API cannot be a better way for someone trying to learn HQL. They are different things - while I agree criteria is better and more object oriented for most of the tasks; hql has it's own use and comes in handly when criteria api isn't feasible
1

I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql

So the thing is you just have to write a query

Query query = session.createQuery("from Employee");

it will give you all the data list but to fetch data from this you have to write this line.

List<Employee> fetchedData = query.list();

As simple as it looks.

Comments

1

Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.

String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
    {
         s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);

   }

for fetch we need Iterator for that define and import package.

Comments

0
Query query = session.createQuery("from Employee");

Note: from Employee. here Employee is not your table name it's POJO name.

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.