我在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