Reputation: 1013
I have a project in Spring 3.1 and Hibernate 3. I am trying to define my DAOs. I have an abstract DAO class with methods for getting the session, committing, rollback, etc. My problem is getting the SessionFactory injected into this class. I am wondering if there is a better way of defining this class. Thanks Eric
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);
}
}
Upvotes: 1
Views: 235
Reputation: 242786
@Autowired
doesn't work on static
fields.
Controlling transactions from DAOs doesn't make much sense because transaction boundaries are usually defined in service layer, so that single transaction can involve multiple DAOs.
Why do you need all these stuff? Spring can do it for you implicitly, see 10. Transaction Management and 13.3 Hibernate. All you need is to define transaction boundaries (using @Transacional
or TransactionTemplate
) and obtain the current session in your DAOs as sessionFactory.getCurrentSession()
.
Upvotes: 4