我在Spring 3.1和Hibernate 3中有一个项目。我试图定义我的DAO。我有一个抽象的DAO类,其中包含获取会话,提交,回滚等方法。我的问题是将SessionFactory注入到此类中。我想知道是否有更好的方式来定义这个类。感谢埃里克休眠/春季新手架构
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractDAO {
@Autowired
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
protected static Session getSession() {
Session session = threadLocal.get();
if (session == null) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
protected void begin() {
getSession().beginTransaction();
}
protected void commit() {
getSession().getTransaction().commit();
}
protected void rollback() {
try {
getSession().getTransaction().rollback();
}
catch (HibernateException ex) {
ex.printStackTrace();
}
close();
}
protected void close() {
try {
getSession().close();
}
catch (HibernateException ex) {
ex.printStackTrace();
}
threadLocal.set(null);
}
}
你对我的看法很简单... – hvgotcodes