[java] how to fetch data from database in Hibernate

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.

This question is related to java hibernate

The answer is


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.


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 */


            }

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.


try the class-name

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

instead of the table name

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

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

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