Creating Hibernate Session with Database

  1. model.dao.interfaces.EmployeeDAOInterface.java

 

package model.dao.interfaces;

import java.util.List;
import model.Employee;

/**
 *
 * @author Shailesh Sonare
 */
public interface EmployeeDAOInterface {
    public List getAllEmplyees();
}

 

2. model.dao.EmployeeDAO.java

 

package model.dao;

import java.util.Iterator;
import java.util.List;
import model.Employee;
import model.dao.interfaces.EmployeeDAOInterface;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Shailesh Sonare
 */
public class EmployeeDAO implements EmployeeDAOInterface {

    @Override
    public List getAllEmplyees() {
        Configuration cnf = new Configuration();
        cnf.configure("hibernate.cfg.xml");
        
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cnf.getProperties());
        
        SessionFactory sf = cnf.buildSessionFactory(ssrb.build());
        Session session = sf.openSession();
        
        String hql = "FROM Employee where id = 2";
        
        List list = session.createQuery(hql).list();
        
        for(Iterator iterator = list.iterator(); iterator.hasNext();) {
            Employee e = (Employee)iterator.next();
            
            System.out.println(e.getName());
        }
        
        return list;
    }
    
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *