1

这是我之前的问题的延续:Spring MVC with Hibernate Data Saving Error

根据那里的答案解决了先前的错误。现在我想在表单中显示保存的值。

    @RequestMapping("manage")
public String manage(@ModelAttribute Automotive automotive,
        BindingResult result, ModelMap model) {

    List<Company> companies = companyService.listAllCompanies();
    model.addAttribute("companies", companies);

    automotiveService.addAutomotive(automotive);
    return "automotive/index";
}

我的观点是

<form:form action="/Automotive/manage" modelAttribute="automotive">
    <form:hidden path="id" />
    Name : <form:input path="name" />
    Description : <form:input path="description" />
    Type : <form:input path="type" />
    Company : <form:select path="company" items="${companies}"
        itemLabel="name" itemValue="id" title="Company"/>
    <input type="submit" />
</form:form>

我能够正确保存数据,但返回时显示抛出错误:

org.apache.jasper.JasperException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session


root cause: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
biz.canisrigel.automirror.model.Company_$$_javassist_0.toString(Company_$$_javassist_0.java)
org.springframework.util.ObjectUtils.nullSafeToString(ObjectUtils.java:610)

更新

在使用 Kevin 对 OpenSessioninViewFilter 的建议时,由于我使用的是会话工厂接口,因此我得到了 No qualifying bean of type [javax.persistence.EntityManagerFactory] ​​is defined 的错误。

4

3 回答 3

1

您尝试访问视图中没有 Hibernate 会话的延迟加载实体,因此它无法调用数据库。

Spring 提供了一个OpenSessionInViewFilter将 延伸Session到视图的方法。它是通过将以下内容添加到您的 web.xml 来配置的:

<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
于 2013-05-09T09:08:00.750 回答
0
org.hibernate.LazyInitializationException

这与Hibernate问题有关。

通过这种感觉,就像您Parent从包含对象的数据库中获取了对象一样Child。并且您试图从控制器中的父对象访问子对象可能会导致问题。

Check Parent entity fetch Lazy false
于 2013-05-09T09:05:16.590 回答
0

使用 sessionfactory 接口时使用

<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
于 2013-05-09T12:17:40.050 回答