Home > Java > javaTutorial > body text

Examples of handling failed lazy loading of fetch=FetchType.LAZY in hibernate

黄舟
Release: 2017-09-29 10:24:51
Original
1590 people have browsed it

To deal with this lazy loading problem, the final approach is to use a support class for Hibernate provided by Spring. Its main meaning is to open the Hibernate Session when a page request is initiated, and maintain this Session so that Hibernate's Session The life cycle becomes longer until the request ends, which is implemented through a Filter. So, if we now want to use Hibernate's lazy loading feature, and also want to extend the life cycle of the session and display the data on the page (through the action layer), then we have to add the following configuration to the web.xml file:


    <!-- 配置Spring的用于解决懒加载问题的过滤器 -->  
     <filter>  
        <filter-name>OpenSessionInViewFilter</filter-name>  
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  
     </filter>  
     <filter-mapping>  
        <filter-name>OpenSessionInViewFilter</filter-name>  
        <url-pattern>*.action</url-pattern>  
     </filter-mapping>
Copy after login

Note: 1) OpenSessionInViewFilter is the filter name, *.action means intercepting all actions, or /*

  2) Non-web page request ( Such as scheduled tasks) can be processed in the following way (the Hibernate.initialize(Object proxy) method forces loading, which is equivalent to dynamically changing to lazy=fals)


/**
 * @Author masl - 2017/9/28 14:22
 * @param setRepaymentId
 * @param initSubs :是否初始化关联表数据
 * @return
 */
@Override
public SetRepayment findSetRepaymentById(Integer setRepaymentId, boolean initSubs) {
    SetRepayment setRepayment = null;
    if (setRepaymentId != null) {
        setRepayment = setRepaymentDao.get(setRepaymentId);
        if (setRepayment != null && initSubs) {
            Hibernate.initialize(setRepayment.getSetIncomes());
        }
        return setRepayment;
    }
    return null;
}
Copy after login

The above is the detailed content of Examples of handling failed lazy loading of fetch=FetchType.LAZY in hibernate. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template