子类继承HibernateDaoSupport后,由于HibernateDaoSupport,setSessionFactory是使用final修飾的,無法重寫,沒有辦法使用註解的方式注入sessionFactroy
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}
我们可以变通一下,自己定义一个方法,这个方法去调用hibernateDaoSupport 中的setSessionFacotry方法,达到注入sessionFactory的目的。
@Autowired
public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
this.getHibernateTemplate().save()方法报错的问题
InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
两步:
1.web.xml中打开懒加载
<!-- 懒加载 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.在执行save之前加这么一句:this.getHibernateTemplate().getSessionFactory().getCurrentSession().setFlushMode(FlushMode.AUTO)
this.getHibernateTemplate().getSessionFactory().getCurrentSession().setFlushMode(FlushMode.AUTO);
this.getHibernateTemplate().save(historyArcticlesRequest);