java - 使用 jpa 和 hibernate 在 spring 中延迟加载实体

标签 java spring hibernate lazy-loading spring-transactions

我将 Spring 与 JPA 和 Hibernate 一起使用。我有一些用 @Repositoy 注释的 DAO 类和一些 Controller 类。当我在 Controller 中调用 dao 的方法之一来加载一些实体时,我会返回实体,之后,我想要获取存储在第一个加载实体的字段中的其他一些实体。但那时spring已经关闭了session,懒加载已经不可能了。

我的 db.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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" default-autowire="byName">

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="jpaVendorAdapter" />
    </bean> -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="${db.dialect}" />
            </bean>
        </property>     
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
</beans>

Dao中的方法注释如下:

@Transactional(readOnly = true, propagation=Propagation.REQUIRED)

现在我想做这样的事情:

@Controller
public class HomeController{

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<String> home(){
        ...
        User user = userDao.findUser(id);
        Set<Order> orders = user.getOrders();
        ...
    String myResult = ...;
    return jsonService.generateResponse(myResult);
    }

}

@Repository
public class UserDao{

    @PersistenceContext
    private EntityManager entityManager;

    public User findUser(Integer id){
        return entityManager.find(User.class, id);
    }
}

订单集应该是延迟加载的,但我得到以下异常:org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 org.hibernate.LazyInitializationException:未能延迟初始化角色集合:...,没有 session 或 session 已关闭

根本原因:org.hibernate.LazyInitializationException:未能延迟初始化角色集合:...,没有 session 或 session 被关闭

我尝试在 Controller wirt @Transactional 中注释该方法,并在 db.xml 中的注释驱动属性中设置 mode="aspectj",但没有任何效果。有没有办法延迟加载用户的订单?

如有任何帮助,敬请期待!

最佳答案

您可以使用特殊过滤器在 Web View 中获取 session 。添加到您的 web.xml

<filter>
    <filter-name>jpaFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>jpaFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

过滤器的工作原理如下:

  • 过滤器拦截 servlet 请求
  • 过滤器打开一个EntityManager并将其绑定(bind)到当前线程
  • 调用 Web Controller
  • 网络 Controller 调用服务
  • 事务拦截器开始 新事务,检索线程绑定(bind)的 EntityManager 并绑定(bind) 它到交易
  • 服务被调用,执行一些操作 EntityManager,然后返回
  • 事务拦截器刷新 然后EntityManager提交事务
  • 网络 Controller 准备 查看,然后返回
  • View 已构建
  • 过滤器关闭 EntityManager 并 将其与当前线程解除绑定(bind)

关于java - 使用 jpa 和 hibernate 在 spring 中延迟加载实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303655/

相关文章:

javascript - 如何在 Backbone.js 中获取错误消息?

java - Spring - 将存储库 Autowiring 到服务中时出现 NoSuchBeanDefinitionException

java - 无法使用 JpaTransactionManager 在 Spring 测试中保留实体

sql - 如何更新作为组合键的一部分并在oracle SQL中充当一个表的主键和其他表中的外键的列

java - 使用 javascript 实现交易/报价 API(c++ 或 Java)

java - 返回随机 boolean 值并用于引导 "if"语句

java - 如何在 netbeans 中同时调试多个线程/runnable

java - 如何在模板 Thymeleaf 中调用使用 Java (Spring) 创建的函数?

java - 防止 Controller 响应

java - Hibernate - Java分页 - 内存不足异常