我遇到了 spring + hibernate 的常见错误,但无法修复它。我有 2 个具有一对多关系的表:每个 Bsc 有许多 Cell
我的 hibernate 配置:
<class name="Bsc" table="bsc">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" />
<set name="cells">
<key column="bsc_id" />
<one-to-many class="Cell" />
</set>
</class>
<class name="Cell" table="cell">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<many-to-one name="bsc" column="bsc_id" not-null="true" />
</class>
我的道:
public class BscDaoImpl extends HibernateDaoSupport implements BscDao {
@Override
public Bsc get(int id) {
return (Bsc) getHibernateTemplate().get(Bsc.class, id);
}
@Override
public void save(Bsc bsc) {
getHibernateTemplate().saveOrUpdate(bsc);
}
}
我的 Controller :
public class BscFormController extends SimpleFormController {
private BscDao bscDao;
public void setBscDao(BscDao bscDao) {
this.bscDao = bscDao;
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String id = request.getParameter("id");
if (!StringUtils.isBlank(id)) {
return bscDao.get(new Integer(id));
}
return new Bsc();
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Bsc bsc = (Bsc) command;
String success = getSuccessView();
bscDao.save(bsc);
return new ModelAndView(success);
}
}
在我看来,我有一个用于创建/编辑 bsc 信息的表单。另外,我想列出这个bsc的所有单元格,所以我在web.xml中配置延迟加载
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>mySessionFactory</param-value>
</init-param>
</filter>
我的问题:按下“保存”按钮时无法保存对象(如果删除 OpenSessionInViewFilter 配置,它就可以保存)。
我添加了 TransactionManager 配置:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
但是还是不行。我错过了什么吗?
最佳答案
我已经通过在 web.xml 中设置 OpenSessionInViewFilter 解决了这个问题
<filter>
<filter-name>lazyLoadingFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
问候
关于hibernate - Spring OpenSessionInViewFilter : can't save object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114616/