我想用spring配置spring,並且我注意到一件事情我無法得到:當我嘗試從Container獲取Session對象時。
Bean.getBean(GenericDao.class).getCurrentSession();
我只能關閉會議。
如果我將與openSession()
方法相同 - 我將收到有效會話。
所以接下來的問題是:爲什麼?我一直在谷歌研究,但沒有找到答案。有人知道嗎?爲什麼在彈簧之外的Iget關閉會話上下文
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
@Transactional (propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
public abstract class GenericDao {
@Autowired
protected SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Session openSession() {
return sessionFactory.openSession();
}
public void saveOrUpdate(final Serializable object) {
getCurrentSession().saveOrUpdate(object);
}
public void delete(final Serializable object) {
getCurrentSession().delete(object);
}
public void save(final Serializable object) {
getCurrentSession().save(object);
}
public void update(final Serializable object) {
getCurrentSession().update(object);
}
public void merge(final Serializable object) {
getCurrentSession().merge(object);
}
@SuppressWarnings ("unchecked")
public <T> List<T> list(final Class<T> clazz) {
return getCurrentSession().createCriteria(clazz).list();
}
@SuppressWarnings ("unchecked")
public <T> T get(final Class<T> clazz, final Serializable id) {
return (T) getCurrentSession().get(clazz, id);
}
}
@Repository
@Primary
class GenericDaoImpl extends GenericDao {
}
你是否試圖說,是春天的上下文出生在春天之一,這意味着它不可能從'getCurrenSession()'方法獲得'會話'活着以外的春天上下文嗎?我理解你了嗎? – Dante
在你的情況下,hibernate上下文由Spring管理,並且可以從'getCurrenSession()'方法獲得會話,但是你需要正確配置'hibernate.current_session_context_class'屬性值,因爲默認值是「JTA」即一個已經存在的jta事務,它可以在獲取它之前關閉你的會話(會話)。 –
好吧,情況變得更加清楚了......感謝您的回覆,我會檢查它 – Dante