package org.seasar.hibernate.dao.impl;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.hibernate.Criteria;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.expression.Expression;

import org.seasar.hibernate.HibernateRuntimeException;
import org.seasar.hibernate.S2Session;
import org.seasar.hibernate.S2SessionFactory;

/**
 * @author kenichi_okazaki 
 */
public class AutoQueryCommand extends AbstractQueryHibernateCommand {

	public AutoQueryCommand(S2SessionFactory s2sessionFactory,Class beanClass, Method method) {
		super(s2sessionFactory, beanClass,method);

	}

	/*
	 * (”ñ Javadoc)
	 * 
	 * @see org.srasar.hibernate.dao.HibernateCommand#execute(org.seasar.hibernate.S2Session,
	 *      java.lang.Object[])
	 */
	public Object execute( Object[] args) {

		List ret = autoExecute(getS2Session(), args);
		return getReturnObject(getMethod(),ret);

	}

	private List autoExecute(S2Session s2session, Object[] args) {
		String[] ArgNames = getArgNames();
		
		Criteria criteria = s2session.createCriteria( getBeanClass() );
		for (int i = 0; i < ArgNames.length; ++i) {
			if (args[i] != null) {
				criteria.add(Expression.eq(ArgNames[i], args[i]));
			}
		}
		
		try {
			return criteria.list();
		} catch (HibernateException ex) {
			throw new HibernateRuntimeException(ex);
		}
	}

}