M
M
MrD2013-09-03 13:16:28
Java
MrD, 2013-09-03 13:16:28

Spring, Hibernate and Lazy initialize?

Hello!
There is an error of the following kind when I deduce the data from a DB on the controller.

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ua.home.entity.Question.answers, no session or session was closed


Essence

@Entity<br>
    @Table(name = "Question")<br>
    public class Question implements Serializable{<br>
<br>
    @Id<br>
    @GeneratedValue(strategy=GenerationType.IDENTITY)<br>
    private int id;<br>
<br>
    private String question;<br>
<br>
    @OneToMany(mappedBy="question")<br>
    private List<Answer> answers;<br>
    .....<br>


DAO
@Repository<br>
@Transactional <br>
public class QuestionDAOImpl implements QuestionDAO {<br>
<br>
  @Autowired<br>
  private SessionFactory sessionFactory;<br>
  <br>
  @SuppressWarnings("unchecked")<br>
//	@Transactional<br>
  public List<Question> getQuestion() {<br>
    return sessionFactory.getCurrentSession().createQuery("from Question").list();<br>
  }<br>
}<br>


Service
@Service<br>
public class QuestionServiceImpl implements QuestionService {<br>
<br>
    @Autowired<br>
    private QuestionDAO questionDAO;<br>
<br>
    @Transactional<br>
    public List<Question> getQuestion() {<br>
        return questionDAO.getQuestion();<br>
    }<br>
}<br>


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


Tried using OpenSessionInViewFilter, with and without url-pattern

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


Tried using EAGER, different error

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError


I also found advice to use Hibernate.initialize, but I don’t understand how to apply it exactly here, if possible in general.

Added SessionFactoryUtils to data.xml, also found this advice, didn't help.

<?xml  version="1.0" encoding="UTF-8"?><br>
<beans xmlns="http://www.springframework.org/schema/beans"<br>
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"<br>
    xmlns:context="http://www.springframework.org/schema/context"<br>
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"<br>
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"<br>
    xmlns:util="http://www.springframework.org/schema/util"<br>
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br>
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd<br>
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd<br>
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd<br>
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd<br>
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"><br>
<br>
    <tx:annotation-driven  transaction-manager="transactionManager" /><br>
<br>
    <bean id="transactionManager"<br>
        class="org.springframework.orm.hibernate3.HibernateTransactionManager"><br>
        <property name="sessionFactory" ref="sessionFactory" /><br>
    </bean><br>
<br>
    <bean id="messageSource"<br>
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><br>
        <property name="basename" value="classpath:messages" /><br>
        <property name="defaultEncoding" value="UTF-8" /><br>
    </bean><br>
<br>
    <bean id="propertyConfigurer"<br>
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"<br>
        p:location="/WEB-INF/jdbc.properties" /><br>
<br>
    <bean id="dataSource"<br>
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"<br>
        p:driverClassName="${jdbc.driverClassName}" <br>
        p:url="${jdbc.databaseurl}"<br>
        p:username="${jdbc.username}" <br>
        p:password="${jdbc.password}" /><br>
<br>
<bean name="hibernateSession" class="org.springframework.orm.hibernate3.SessionFactoryUtils" factory-method="getSession"<br>
  scope="prototype"><br>
        <constructor-arg index="0" ref="hibernateSessionFactory"/><br>
        <constructor-arg index="1" value="false"/><br>
        <aop:scoped-proxy/><br>
    </bean><br>
<br>
    <bean id="sessionFactory"<br>
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><br>
        <property name="dataSource" ref="dataSource" /><br>
        <property name="configLocation"><br>
            <value>classpath:hibernate.cfg.xml</value><br>
                <!-- <value>classpath*:**/hibernate.cfg.xml</value> --><br>
<br>
        </property><br>
        <property name="configurationClass"><br>
            <value>org.hibernate.cfg.AnnotationConfiguration</value><br>
        </property><br>
        <property name="hibernateProperties"><br>
            <props><br>
                <prop key="hibernate.show_sql">true</prop><br>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop><br>
                <prop key="hibernate.connection.charSet">UTF-8</prop><br>
            </props><br>
        </property><br>
    </bean><br>
<br>
</beans><br>


What else can be the solution to my problem or maybe I made a mistake somewhere?

Thanks

UPDATE

@Entity<br>
public class Answer  implements Serializable {<br>
  <br>
<br>
  @Id<br>
  @GeneratedValue(strategy=GenerationType.IDENTITY)<br>
//	@GeneratedValue<br>
  private int id;<br>
<br>
  private String answer;<br>
<br>
  private byte isCorrect;<br>
<br>
  @ManyToOne<br>
  @JoinColumn(name="QuestionID")<br>
  private Question question;<br>
.........<br>
       @Override<br>
  public String toString() {<br>
    return "Answer [id=" + id + ", answer=" + answer + ", isCorrect="<br>
        + isCorrect + ", questions=" + question + "]";<br>
  }<br>

In general, if you remove the line + ", questions=" + question, then there is no error. But as a result of the request, there is no FK on the Question entity.

toString Question

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


PS How can an author respond to a user's comment? It used to work, now I don’t have to, it seems.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MrD, 2013-09-03
@MrD

The problem was that I made a selection from one entity that was associated with the second, which in turn was with the first. The result was a loop.
The first solution was to remove Answer from the toString answers="+ answers + method.
The second option is to make a request using JOIN, though I had another problem with it, links are returned instead of values.

D
Divers, 2013-09-03
@Divers

If you have Hibernate 4.16 + then add to the config:

<prop key="hibernate.enable_lazy_load_no_trans">true <prop/>

Then the hibernate itself will open the session.
hibernate.onjira.com/browse/HHH-7457

J
javax, 2013-09-03
@javax

Lazy doesn't work because the session has closed and it can no longer access the database for answers.
We need to understand why eager does not work, look at the error stack

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question