【问题标题】:Spring, Hibernate and Lazy initializeSpring,Hibernate 和 Lazy 初始化
【发布时间】:2013-09-03 09:56:16
【问题描述】:

我在 SO 上阅读了很多关于此问题的帖子,但没有为我找到任何解决方案。

我有什么

错误

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ua.home.bla.entity.Question.answers, no session or session was closed

实体

 @Entity
    @Table(name = "Question")
    public class Question implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    private String question;

    @OneToMany(mappedBy="question")
    private List<Answer> answers;
    .....

   @Repository
@Transactional 
public class QuestionDAOImpl implements QuestionDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
//  @Transactional
    public List<Question> getQuestion() {
        // TODO Auto-generated method stub
        return sessionFactory.getCurrentSession().createQuery("from Question").list();
    }
}

服务

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionDAO questionDAO;


    @Transactional
    public List<Question> getQuestion() {
        return questionDAO.getQuestion();
    }

}

控制器

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Model model){
        List<Question> qu =questionService.getQuestion();
        System.out.println(qu);
        return "home";
    }
}

我尝试使用 OpenSessionInViewFilter,有和没有 url-pattern

<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 

我尝试使用注释EAGER,其他错误

org.springframework.web.util.NestedServletException:处理程序处理失败;嵌套异常是 java.lang.StackOverflowError

我不知道如何在我的代码 Hibernate.initialize 中使用这个解决方案

在 data.xml 中添加 SessionFactoryUtils,来自 SO 中的一些答案

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <tx:annotation-driven  transaction-manager="transactionManager" />


    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>


    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}" 
        p:url="${jdbc.databaseurl}"
        p:username="${jdbc.username}" 
        p:password="${jdbc.password}" />

<bean name="hibernateSession" class="org.springframework.orm.hibernate3.SessionFactoryUtils" factory-method="getSession"
  scope="prototype">
        <constructor-arg index="0" ref="hibernateSessionFactory"/>
        <constructor-arg index="1" value="false"/>
        <aop:scoped-proxy/>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
                <!-- <value>classpath*:**/hibernate.cfg.xml</value> -->

        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
            </props>
        </property>
    </bean>

</beans>

对解决我的问题有什么想法吗?也许我错过了什么?

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="ua.home.bla.entity.Answer" />
        <mapping class="ua.home.bla.entity.Question" />
        <mapping class="ua.home.bla.entity.Contact" />
    </session-factory>
</hibernate-configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!--  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/root-context.xml
        </param-value>
    </context-param>

    <!-- Container Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--
    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>    -->

    <!-- Base Servlet -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <filter>
        <filter-name>charsetFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>charsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<!-- 
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> -->


</web-app>

根上下文.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">



    <!--  (@Annotation-based configuration)-->
    <context:annotation-config />

    <!-- (@Component, @Service)  -->
    <context:component-scan base-package="ua.home.bla.dao" />
    <context:component-scan base-package="ua.home.bla.service" />

    <!-- (Data Access Resources) -->
    <import resource="data.xml" />

</beans>

控制器.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Dir with conrollers-->

    <context:component-scan base-package="ua.home.bla.web" />

</beans>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- @Controller etc. -->
    <annotation-driven />

    <!-- css, javascript in dir webapp/resources  -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- jsp /WEB-INF/views -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!-- controllers settings -->
    <beans:import resource="controllers.xml" />

</beans:beans>

谢谢!

----更新-----

问题实体方法 toString

@Override
    public String toString() {
        return "Question [id=" + id + ", question=" + question + ", answers="
                + answers + "]";
    }

回答实体方法toString

@Override
public String toString() {
    return "Answer [id=" + id + ", answer=" + answer + ", isCorrect="
            + isCorrect + ", questions=" + question + "]";
}

如果我删除

", questions=" + 问题

没有错误,但没有关于问题实体的信息。不是完整的结果。

回答实体

@Entity
public class Answer  implements Serializable {


    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    private String answer;

    private byte isCorrect;

    @ManyToOne
    @JoinColumn(name="QuestionID")
    private Question question;

【问题讨论】:

  • 您能否发布正确的 dao... 并发布我们的 hibernate.cfg。关于配置的小提示使用AnnotationSessionFactoryBean 而不是LocalSessionFactoryBean 可以节省您指定configurationClass 属性的时间。此外,由于您注入了数据源,您的 hibernate.connection.charSet 也毫无用处。我也希望你不要使用 bean hibernateSession,因为那是行不通的。
  • 哦!对不起。正确的 DAO 只需将联系人替换为问题(无法编辑我的帖子)。
  • 你是如何加载这些文件的(在你的 web.xml 中)你能显示。你如何实例化你的 @Service 等 bean。请贴出相关配置。
  • 您在哪一行出现错误?
  • 几分钟添加所有其他文件

标签: spring hibernate spring-mvc jpa lazy-initialization


【解决方案1】:

您的配置缺少OpenSessionInViewFilterfilter-mapping,否则它将什么也不做。旁边您的过滤器已被注释掉。

添加

<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <servlet-name>appServlet</servlet-name>
</filter-mapping>

并激活您的过滤器。

【讨论】:

  • 我做了,但没有帮助。找出真正的问题在哪里。在我的实体中,我覆盖了 toString()。见更新。我不知道如何使 toString 正确。
  • 没有过滤器它永远不会工作。但是,您的 to 字符串将导致StackOverFlow...Question 将调用toString,这将导致Answer.toString,这导致Question.toString,这导致Answer.toString,你可能明白了.您处于无限循环中。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2012-05-03
相关资源
最近更新 更多