package com.itjob.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Hibernate数据库操作实现类. 
 */
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
	public void deleteObject(Object obj) throws HibernateException {
		this.getHibernateTemplate().delete(obj);
	}

	public void deleteObject(Class class1,
			Serializable serializable) throws HibernateException {
		getHibernateTemplate().delete(getObject(class1, serializable));
        getHibernateTemplate().flush();
	}
	
	public void updateObject(Object obj) throws HibernateException {
		this.getHibernateTemplate().update(obj);
	}

	public void saveObject(Object obj) throws HibernateException {
		this.getHibernateTemplate().save(obj);
	}

	public Object getObject(Class class1,
			Serializable serializable) throws HibernateException {
		return getHibernateTemplate().get(class1, serializable);
	}
	
	public List hqlQuery(String hsql) throws HibernateException {
		return query(hsql, null);
	}
	
	public List hqlQuery(String hsql, Object obj) throws HibernateException {
		return query(hsql, obj);
	}

    private List query(final String hsql, final Object obj) throws HibernateException {	
        List queryList =  (List)getHibernateTemplate().execute(
        		//创建匿名内部类
                new HibernateCallback() {
                    public Object doInHibernate(Session session) 
                            throws HibernateException, SQLException {
                        Query query = session.createQuery(hsql);

                        if (obj != null) {
                            if (obj instanceof Map) {
                                String as[] = query.getNamedParameters();
                                for (int k1 = 0; k1 < as.length; k1++) {
                                    query.setParameter(as[k1],
                                            ((Map) obj).get(as[k1]));
                                }
                            } else if (obj instanceof Object[]) {
                                for (int i1 = 0; 
                                        i1 < ((Object[]) obj).length; i1++) {
                                    query.setParameter(i1, 
                                            ((Object[]) obj)[i1]);
                                    
                                }
                            } else {
                                query.setParameter(0, obj);
                            }
                        }
                        return query.list();
                    }
               }
           );

        return queryList;
    }
}
