Spring MVC中的错误 - 显示具有选择项的Modal属性的表单

时间:2013-05-09 09:00:43

标签: java spring hibernate spring-mvc

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

之前的错误是根据那里的答案解决的。现在我想在表单中显示Saved值。

    @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建议时,我得到了错误,因为我正在使用会话工厂接口,因此定义了类型为[javax.persistence.EntityManagerFactory]的无限定bean。

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

org.hibernate.LazyInitializationException

这与Hibernate问题有关。

通过性别歧视,它告诉您已从DB中获取Parent对象,其中包含Child对象。并且您尝试从Controller中的Parent访问子对象可能会导致问题。

Check Parent entity fetch Lazy false

答案 2 :(得分: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>