package examples.hibernate.dao;

import java.util.List;

import net.sf.hibernate.Criteria;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.expression.Example;

import org.seasar.hibernate.HibernateRuntimeException;
import org.seasar.hibernate.S2Session;
import org.seasar.hibernate.S2SessionFactory;
import examples.hibernate.entity.Employee;

public class EmployeeDaoImpl implements EmployeeDao {

	private static final String HQL = "from Employee where empno = ?";
	private S2SessionFactory sessionFactory_;

	public EmployeeDaoImpl(S2SessionFactory sessionFactory) { 

		sessionFactory_ = sessionFactory;
	}

	public Employee getEmployee(int empno) {
		List result = sessionFactory_.getSession().find(
			HQL, new Integer(empno), Hibernate.INTEGER);
		if (result.size() > 0) {
			return (Employee) result.get(0);
		} else {
			return null;
		}
	}
	
	public void save(Employee employee) {
		sessionFactory_.getSession().save(employee);
	}
	
	public Employee getEmployeeQBE(int empno){
		
		Employee employee = new Employee();
		employee.setEmpno(new Integer(empno));
		employee.setEname("JAMES");
			
//		Example example = Example.create(employee).excludeProperty("deptno");
		Example example = Example.create(employee).excludeZeroes()       ;
	
		S2Session session = sessionFactory_.getSession();
		Criteria criteria = session.createCriteria(Employee.class);
		criteria.add(example);
		try {
			List result = criteria.list();
			
			   if (result.size() > 0) {
			    return (Employee) result.get(0);
			   } else {
			    return null;
			   }
			   
		} catch (HibernateException e) {
			throw new HibernateRuntimeException(e);
		}	

	}
}
