在搭建框架中,我写了一个基础服务实现类,具体的代码如下:
package cn.tim.common; import java.lang.reflect.ParameterizedType; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * 公共模块的抽取 * @author jintian chen * @date 2016年2月24日 */ <span style="color:#ff6666;">@Service @Lazy</span> public class BaseServiceImpl<T> implements BaseService<T> { //clazz中存储了当前操作的类型 private Class clazz; @SuppressWarnings("rawtypes") public BaseServiceImpl(){ ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass(); clazz = (Class)type.getActualTypeArguments()[0]; } @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } protected Session getSession() { return sessionFactory.getCurrentSession(); // return sessionFactory.openSession(); } @Override public void save(T t) { getSession().save(t); } @Override public void update(T t) { getSession().update(t); } @Override public void delete(int id) { String hql = "DELETE "+ clazz.getSimpleName() +" WHERE id=:id"; getSession().createQuery(hql).setInteger("id", id).executeUpdate(); } @SuppressWarnings("unchecked") @Override public T get(int id) { return (T)getSession().get(clazz, id); } @SuppressWarnings("unchecked") @Override public List<T> query() { String hql = "FROM " + clazz.getSimpleName(); return getSession().createQuery(hql).list(); } }
然后,我用其他类调用该基础类,在其他的中调用update,此时不起作用,报的错误是:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
我还以为是代码这句错误:
protected Session getSession() { return sessionFactory.getCurrentSession(); // return sessionFactory.openSession(); }解决办法是:添加事务注解:
@Service
@Transactional
@Lazy
public class BaseServiceImpl<T> implements BaseService<T> {
在配置文件中添加:
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
以上方法可以解决该问题。
参考文献:http://fengzhiyin.iteye.com/blog/714686