spring3.1 + hibernate4.1 + struts2.3整合,dao层该怎么写

2025-04-30 19:10:14
推荐回答(1个)
回答1:

// 让你的Dao继承这个DaoSupport
// 注意:

// 1、需要Spring注入sessionFactory
// 2、需要Spring声明式事物
// 3、有其他问题email我,fuhaiwei@126.com

package com.fuhaiwei.dao;

import static org.hibernate.criterion.Restrictions.eq;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DaoSupport {

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

protected Session getSession() {
return sessionFactory.getCurrentSession();
}

protected void save(Object obj) {
getSession().save(obj);
}

protected T get(Class clazz, int id) {
return (T) getSession().get(clazz, id);
}

protected List findByProperty(Class clazz, String property, Object value) {
return getSession().createCriteria(clazz).add(eq(property, value)).list();
}

protected List findAll(Class clazz) {
return getSession().createCriteria(clazz).list();
}

protected void update(Object obj) {
getSession().update(obj);
}

protected void delete(Class clazz, int id) {
getSession().delete(get(clazz, id));
}

protected void delete(Object obj) {
getSession().delete(obj);
}

}