Hibernate读取数据

来源:互联网 发布:淘宝新开店铺没人光顾 编辑:程序博客网 时间:2024/05/17 23:44


public interface GenericDao<T, PK> {    public Session getSession()    public void saveOrUpdate(T e);    public void save(T e);    public void update(T e);}

@Repository(value = "genericDao")public class GenericDaoImpl<T, PK extends Serializable> implements        GenericDao<T, PK> {    @Resource(name = "sessionFactory")    private SessionFactory sessionFactory;    public Session getSession() {        // 事务必须(Required)是开启的,否则获取不到        return sessionFactory.getCurrentSession();    }     public void saveOrUpdate(T e) {        getSession().saveOrUpdate(e);    }    public void save(T e) {        getSession().save(e); // 这里需要测一下需要不需要返回E    }    public void update(T e) {        getSession().update(e);    }}


public interface ChartDao extends GenericDao<Chart,Long>{    public List<Chart> getChartList(String month,String area);    public Long getCountByIncomeId(String incomeId);}



@Repository("chartDao")public class ChartDaoImpl extends GenericDaoImpl<Chart, Long> implements ChartDao {    @Override    public List<Chart> getChartList(String month, String area) {        List<Chart> list = new ArrayList<Chart>();        //查询方式一:通过标准SQL查询//        StringBuilder sb = new StringBuilder();//        sb.append("select * from TEST_CHART WHERE STATIS_MONTH='" + month + "' AND AREA_CODE='" + area + "'");//        list = getSession().createSQLQuery(sb.toString()).addEntity(Chart.class).list();        //查询方式二:通过Hibernate的Criteria查询,Criteria查询对面向对象进行了封装//        Criteria criteria = getSession().createCriteria(Chart.class);//        if (!(null == month && "".equals(month))) {//            criteria.add(Restrictions.eq("month", month));//        }//        if (!(null == area && "".equals(area))) {//            criteria.add(Restrictions.eq("area", area));//        }//        list=criteria.list();        //查询方式三:通过HQL(Hibernate Query Language)查询,Query查询        StringBuilder sb = new StringBuilder();        sb.append("FROM Chart model where model.month=:tempMonth");        sb.append(" AND ");        sb.append("model.area=:tempArea");        Query q = getSession().createQuery(sb.toString());        q.setParameter("tempMonth", month);        q.setParameter("tempArea", area);        list = q.list();        return list;    }    @Override    public Long getCountByIncomeId(String incomeId) {//    Session session = super.getSession();  //    long count = (Long) session.createQuery("select count(model) from Chart model").uniqueResult(); //    session.close();          //查询count,通过HQL查询        Query q = getSession().createQuery("select count(c) from Chart c where c.incomeId=:strIncomeId");        q.setParameter("strIncomeId", incomeId);        long count = (Long) q.uniqueResult();        return count;    }}
原创粉丝点击