package org.tarena.dao; import java.sql.SQLException;
import java.util.List; import javax.annotation.Resource; import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.tarena.entity.Cost; @Repository
@Scope("prototype")
public class CostDaoImpl extends HibernateDaoSupport implements CostDao { //用注解才要这么写,否则不用
@Resource//注入sf
public void setMySessionFactory(SessionFactory sf){
super.setSessionFactory(sf);
} /**
* 单个查找
*/
public Cost findById(Integer costId) {
//还有load方法,延迟加载
Cost cost = getHibernateTemplate().get(Cost.class, costId);
return cost;
} /**
* 新增
*/
public void save(Cost cost) {
getHibernateTemplate().save(cost);
} /**
* 删除
*/
public void delete(Cost cost) {
getHibernateTemplate().delete(cost);
} /**
* 更新
*/
public void update(Cost cost) {
getHibernateTemplate().update(cost);
} /**
* 所有查找
*/
public List<Cost> findAll() {
String hql = "from Cost";
List<Cost> list = getHibernateTemplate().find(hql);
return list;
} /**
* 统计个数
*/
public int count() {
String hql = "select count(*) from Cost";
List list = getHibernateTemplate().find(hql);
int count = Integer.parseInt(list.get(0).toString());
return count;
} /**
* 分页查询
*/
public List<Cost> findPage(final int page, final int pageSize) {
List<Cost> list = (List<Cost>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//在方法体中使用session对象
String hql = "from Cost";
Query query = session.createQuery(hql); int begin = (page - 1)*pageSize;
query.setFirstResult(begin);
query.setMaxResults(pageSize);
return query.list();
}
});
return list;
} }