使用HibernateDaoSupport整合spring和hibernate

package com.spring.ch11.dao.hibernate;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.spring.ch11.jdbctemplate.Demo;
import com.spring.ch11.jdbctemplate.IDemoDao;

public class DemoDaoHibernateImpl extends HibernateDaoSupport implements
		IDemoDao {

	@Override
	public List<Demo> getAll() {
		Session session = getSession(false);
		try {
			Query query = session.createQuery("from Demo");
			List<Demo> demoList = query.list();
			if (CollectionUtils.isEmpty(demoList)) {
				throw new RuntimeException();
			}
			return demoList;
		} catch (HibernateException e) {
			throw convertHibernateAccessException(e);
		}
	}

	@Override
	public Demo getById(int id) {
		Session session = getSession(false);
		try {
			Query query = session.createQuery("from Demo d where d.id = :id");
			query.setParameter("id", 1);
			Demo demo = (Demo) query.uniqueResult();
			if (null == demo) {
				throw new RuntimeException();
			}
			return demo;
		} catch (HibernateException e) {
			throw convertHibernateAccessException(e);
		}
	}

}

 

你可能感兴趣的:(DAO,apache,spring,Hibernate,orm)