嗨,我是 spring + hiberent 的新手,我正在尝试编写 GenericDao,但出现以下异常 No Hibernate Session bound to thread,并且配置不允许创建非事务性,请参阅我的代码
通用道
public interface IGenericDao<T> {
public void delete(T obj);
public void saveOrUpdate(T obj);
}
GenericDaoImpl
@Transactional
public class GenericDaoImpl<T> implements IGenericDao<T> {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected SessionFactory getSessionFactory() {
if (sessionFactory == null)
throw new IllegalStateException("SessionFactory has not been set on DAO before usage");
return sessionFactory;
}
@Override
public void delete(T obj) {
getSessionFactory().getCurrentSession().delete(obj);
}
@Override
public void saveOrUpdate(T obj) {
getSessionFactory().getCurrentSession().saveOrUpdate(obj);
}
}
通用服务
public interface IGenericService<T extends Object> {
public void delete(T obj);
public void saveOrUpdate(T obj);
}
IGenericServiceManagerImpl
public class IGenericServiceManagerImpl<T extends Object> implements IGenericService<T> {
@Autowired
IGenericDao<T> genericDao;
@Override
public void delete(T obj) {
// TODO Auto-generated method stub
genericDao.delete(obj);
}
@Override
public void saveOrUpdate(T obj) {
// TODO Auto-generated method stub
genericDao.saveOrUpdate(obj);
}
spring-servlet.xml
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
">
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.codes.gdi.model.EMP</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://spring:myinstance/gdirectorystaging" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
AnyOne帮助我我没有绑定到线程的休眠会话,并且配置不允许在这里创建非事务性会话