【问题标题】:Lazy initialize in Spring MVCSpring MVC中的延迟初始化
【发布时间】:2011-08-15 12:26:58
【问题描述】:

尽管使用下面的配置,但我得到了延迟初始化错误:

org.hibernate.LazyInitializationException: 延迟初始化角色集合失败:beans.Restaurant.tags,没有会话或会话被关闭

这里是

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>RestFinderWebApp</display-name>
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <!-- <welcome-file>index.html</welcome-file> -->
</welcome-file-list>
<!-- Spring security: -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext-security.xml,
        /WEB-INF/spring-servlet.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<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>
<filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
    <filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

spring-servlet.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">

    <context:annotation-config />
    <tx:annotation-driven transaction-manager="txManager" />
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="sessionFactory" />
        </property>
    </bean>
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean class="org.springframework.jmx.export.MBeanExporter">
        <property name="autodetect" value="false" />
        <property name="assembler">
            <bean id="jmxAssembler"
                class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
                <property name="attributeSource">
                    <bean
                        class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
                </property>
            </bean>
        </property>

    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="messages" />

    <bean id="openSessionInViewInterceptor"
        class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="myPersistence" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false" />
                <property name="generateDdl" value="true" /> 
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
            </bean>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        (...)
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                (...)
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.connection.useUnicode">true</prop>
                <prop key="hibernate.connection.characterEncoding">UTF-8</prop>
            </props>
        </property>
    </bean>
    <tx:annotation-driven />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <bean id="myUserDAO" class="dao.UserDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="myRestaurantDAO" class="dao.RestaurantDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean name="/mojekonto.htm" class="web.HomeUserController">
        <property name="userDAO" ref="myUserDAO" />
        <property name="restaurantDAO" ref="myRestaurantDAO" />
        <property name="loggedUser" ref="LoggedUser" />
    </bean>

</beans>

我的控制器:

public class HomeUserController extends MultiActionController {
private UserDAO userDAO;
private TagDAO tagDAO;

public void setTagDAO(TagDAO tagDAO) {
    this.tagDAO = tagDAO;
}

public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
}

private LoggedUser loggedUser;

public void setLoggedUser(LoggedUser loggedUser) {
    this.loggedUser = loggedUser;
}

private RestaurantDAO restaurantDAO;


public void setRestaurantDAO(RestaurantDAO restaurantDAO) {
    this.restaurantDAO = restaurantDAO;
}

private FollowDAO followDAO;

public void setFollowDAO(FollowDAO followDAO) {
    this.followDAO = followDAO;
}
private CommentDAO commentDAO;


public void setCommentDAO(CommentDAO commentDAO) {
    this.commentDAO = commentDAO;
}
@InitBinder
protected void initBinder(HttpServletRequest request,
        ServletRequestDataBinder binder) throws Exception {

    super.initBinder(request, binder);

    binder.registerCustomEditor(List.class, "tags",new CustomCollectionEditor(List.class){

        @Override
        protected Object convertElement(Object element) {
            Tag tag = new Tag();

            if (element != null) {
                int id = Integer.valueOf(element.toString());
                tag.setId(id);
            }
            return tag;
        }
    });

}
public ModelAndView mojekonto(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User user = loggedUser.getLoggedUser();
    ModelMap modelMap = new ModelMap();
    Restaurant restaurant = new Restaurant();
    Restaurant userRestaurant = new Restaurant();
    userRestaurant = restaurantDAO.findRestaurantByUser(user.getUsername());

    modelMap.addAttribute("user", user);
    modelMap.addAttribute("restaurant", restaurant);
    modelMap.addAttribute("userRestaurant", userRestaurant);

    return new ModelAndView("mojekonto", modelMap);
}

我的班级 - 餐厅:

    @Entity
@Table(name="restaurants")
public class Restaurant {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String street;
    private String city;
    private String country;
    private String postal_code;
    private String telephone;
    private String logo;
    private String image;
    private String description;
    private float longitude;
    private float latitude;
    private Date last_update;
    @ManyToMany //it works fine...
    @JoinTable(name="user_restaurant_owner",
            joinColumns={@JoinColumn(name="restaurant_id")},
            inverseJoinColumns={@JoinColumn(name="username")})
    private List<User> owner;
    @ManyToMany //but that doesn't...
    @JoinTable(name="restaurant_tag",
            joinColumns={@JoinColumn(name="restaurant_id")},
            inverseJoinColumns={@JoinColumn(name="tag_id")})
    private List<Tag> tags;
        //getters and setters:

我的观点jsp:

 <c:forEach items="${userRestaurant.tags}" var="current">
do something
</c:forEach>

当它在“{userRestaurant.tags}”时出现错误

【问题讨论】:

    标签: hibernate spring spring-mvc


    【解决方案1】:

    使用 SpringOpenEntityManagerInViewFilter,您的配置看起来是正确的,因此您不应该求助于急切获取或必须预先遍历控制器中的集合。我正在开发的应用程序中具有非常相似的配置和模式,并且它可以正常工作。您可以尝试的一件事是在 DispatcherServlet 配置中添加一个空白上下文位置。没有检查,但我认为它有一些默认行为来根据全局配置加载上下文。实际上,这将导致调度程序 servlet 加载一个单独的上下文,而不仅仅是创建一个空白的上下文,继承自 ContextLoaderListener 创建的上下文(这是您希望它执行的操作)。

    所以,在 DispatcherServlet 的 &lt;servlet&gt; 声明中,添加:

    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    

    更新:使用休眠事务管理器看起来也有点奇怪(考虑到您使用的是 JPA 实体管理器)。尝试将其更改为使用 Jpa 事务管理器。

    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory"/>
        </bean>
    

    更新 2:再次查看您的配置,看起来您正在使用 JPA 和 Hibernate 的奇怪组合。例如,您正在定义两个事务管理器。为什么?此外,您正在使用org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter(即JPA/EntityManager),同时使用org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor(即Hibernate/Session)。你如何在你的 DAO 中查找你的实体?使用休眠会话或 JPA EntityManager?坚持使用 JPA 或 Hibernate 可能会更好地减少冲突。

    我也无法让Open*InViewInteceptor 工作。过滤器看起来更稳定(你有org.springframework.orm.hibernate3.support.OpenSessionInViewFilter,例如,如果你决定使用hibernate pure)。

    【讨论】:

      【解决方案2】:

      您只能访问 DAO 层中的 Hibernate Session。如果您的关联没有配置 FetchType,或者如果他们有 FetchType.LAZY,那么您有两个选择,都在 DAO 内:

      1. 使用Hibernate.initialize
      2. 获取强制 Hibernate 初始化关联的某些方面

      示例 1:Hibernate.initialize(myEntity.getMyAssociation());

      示例 2:

      if(myEntity.getMyAssociation() != null) {
         myEntity.getMyAssociation().size(); // forces the association to be loaded
      }
      

      我通常使用示例 2,因为这样我还可以利用 BatchSize 为 Hibernate 优化延迟获取。

      -----------编辑 1------------

      这种情况下使用 HibernateTemplate 和回调的示例:

         public Restaurant load(final Long id) {
          // need to drop down to Hibernate because of lazy loading, and make sure all properties are loaded
          HibernateCallback<Restaurant> callBack = new HibernateCallback<Restaurant>() {
              public User doInHibernate(Session session) throws HibernateException {
                  Query query = session.createQuery("from Restaurant r where r.id=:id").setInt("id", id);
                  Restaurant restaurant = (Restaurant)query.uniqueResult();
                  Hibernate.initialize(restaurant.getOwner());
                  Hibernate.initialize(restaurant.getTags());             
                  return restaurant;
              }
          };
          return getHibernateTemplate().execute(callBack);
      

      }

      -----------编辑 2----------- 以下是直接在 Hibernate 中执行此操作的方法:

      @Repository
      public class RestaurantDAOImpl implements RestaurantDAO {
          private SessionFactory factory;
      
          @Autowired
          public RestaurantDAOImpl(SessionFactory factory) {
              this.factory = factory;
          }   
      
          public Restaurant load(Long id) {
             Query query = session.createQuery("from Restaurant r where r.id=:id").setInt("id", id);
             Restaurant restaurant = (Restaurant)query.uniqueResult();
             Hibernate.initialize(restaurant.getOwner());
             Hibernate.initialize(restaurant.getTags());
             /* --OR --
             if(restaurant.getTags() != null) {
                restaurant.getTags().size();
             }
             */           
             return restaurant;
          }
      }
      

      【讨论】:

      • 如何在我的班级 restaurantDAO 中做到这一点? : 公共类 RestaurantDAO { 私有 HibernateTemplate hibernateTemplate;公共无效 setSessionFactory(SessionFactory sessionFactory){ this.hibernateTemplate = new HibernateTemplate(sessionFactory); } 公共无效 saveRestaurant(餐厅餐厅){ hibernateTemplate.save(餐厅); } public List GetAllRestaurants(){ return hibernateTemplate.loadAll(Restaurant.class); } }
      • 如果您使用的是 HibernateTemplate,那么您需要通过回调进入 Hibernate。当前的 Spring 标准不是这样做的,而是直接调用 Hibernate。我可以给你看任何一个。你更喜欢哪一个?
      【解决方案3】:

      在引用它们之前尝试 FetchType.EAGER 或手动获取标签。

      @ManyToOne(fetch = FetchType.EAGER)
      @JoinTable(name="restaurant_tag",
      joinColumns={@JoinColumn(name="restaurant_id")},
      inverseJoinColumns={@JoinColumn(name="tag_id")})
      private List<Tag> tags;
      

      【讨论】:

      • 除非您总是希望填充关联,否则配置EAGER fetch 不一定是个好主意。事实上,Hibernate 工具默认将所有关联设置为LAZY。
      • 我同意,EAGER fetch 很危险。我建议您设置 FetchType.EAGER 并查看异常是否已修复,然后在您从数据库加载餐厅时恢复默认的 LAZY fetchtype 并手动获取标签列表(我在您发布的代码中没有看到) .
      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多