package com.tarena.oss.userservice.dao;

import java.sql.SQLException;
import java.util.Collection;

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;

import com.tarena.oss.userservice.pojo.UserService;
import com.tarena.oss.util.PageParameter;

public class UserServiceMgmtDAOHibernate extends HibernateDaoSupport implements UserServiceMgmtDAO {
	
	/**
	 * 删除业务帐号
	 */
	public void deleteUserService(UserService userservice) {
		this.getHibernateTemplate().delete(userservice);
	}

	/**
	 * 插入业务帐号
	 */
	public void insertUserService(UserService userservice) {
		this.getHibernateTemplate().save(userservice);
	}
	
	/**
	 * 更新业务帐号
	 */
	public void updateUserService(UserService userservice) {
		this.getHibernateTemplate().update(userservice);
	}

	/**
	 * 根据id查询业务帐号
	 */
	public UserService queryUserService(Integer id) {
		return (UserService) this.getHibernateTemplate().find("from UserService us where us.id = "+id).get(0);
	}

	/**
	 * 查询所有的业务帐号
	 */
	public Collection<UserService> queryUserServices() {
		return this.getHibernateTemplate().find("from UserService us ");
	}

	/**
	 * 查询业务帐号的总个数
	 */
	public int queryUserServiceCnt() {
		Integer i = (Integer) this.getHibernateTemplate().find("select count(*) from UserService us where 1=1 ").get(0);
		return i;
	}

	/**
	 * 根据查询条件查询业务帐号的总个数
	 */
	public int queryUserServiceCnt(String cond) {
		Integer i = (Integer) this.getHibernateTemplate().find("select count(*) from UserService us where 1=1 "+cond).get(0);
		return i;
	}

	/**
	 * 根据查询条件查询所有的业务帐号
	 */
	public Collection<UserService> queryUserServices(String cond) {
		return (Collection<UserService>) this.getHibernateTemplate().find("from UserService us where 1=1 "+cond);
	}

	public Collection<UserService> queryUserServices(int currentPage) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 根据查询条件和当前页数查询符合条件的业务帐号
	 */
	public Collection<UserService> queryUserServices(String cond,int currentPage) {
		final String qryStr = cond;
		final int startRow = (currentPage - 1) * PageParameter.CNT_EACH_PAGE;
		
		return this.getHibernateTemplate().executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query qry = session.createQuery("from UserService us where 1=1 " + qryStr);
				qry.setFirstResult(startRow);
				qry.setMaxResults(PageParameter.CNT_EACH_PAGE);
				return qry.list();
			}
		});
	}



}
