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

Java 使用jpa和hibernate在spring中延迟加载实体,java,spring,hibernate,lazy-loading,spring-transactions,Java,Spring,Hibernate,Lazy Loading,Spring Transactions,我将Spring与JPA和Hibernate一起使用。我有一些用@Repositoy注释的DAO类和一些控制器类。当我在我的控制器中调用dao的一个方法来加载一些实体时,我会返回实体,然后,我想获取存储在第一个加载实体的字段中的其他实体。但是在那个时候spring已经关闭了会话,延迟加载已经不可能了 My db.xml配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframewo

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

My 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>
现在我想做这样的事情:

@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);
    }
}
@控制器
公共类家庭控制器{
@自动连线
私有UserDao UserDao;
@RequestMapping(value=“/”,method=RequestMethod.GET)
公共响应之家(){
...
User=userDao.findUser(id);
Set orders=user.getOrders();
...
字符串myResult=。。。;
返回jsonService.generateResponse(myResult);
}
}
@存储库
公共类UserDao{
@持久上下文
私人实体管理者实体管理者;
公共用户findUser(整数id){
返回entityManager.find(User.class,id);
}
}
订单集应该是延迟加载的,但我得到以下异常:org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常为org.hibernate.LazyInitializationException:未能延迟初始化角色的集合:…,未关闭任何会话或会话

根本原因:org.hibernate.LazyInitializationException:未能延迟初始化角色的集合:…,未关闭任何会话或会话

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


如有任何帮助,请提前向您表示感谢

您可以使用特殊筛选器在web视图中获取会话。添加到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>

JPA过滤器
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
JPA过滤器
/*
过滤器的工作原理如下:

@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
  • 过滤器拦截servlet请求
  • 过滤器打开EntityManager并将其绑定到当前线程
  • Web控制器被称为
  • Web控制器调用服务
  • 事务拦截器开始 新事务,检索线程绑定的EntityManager并绑定 它与交易有关
  • 服务被调用,使用 EntityManager,然后返回
  • 事务拦截器刷新 EntityManager然后提交事务
  • Web控制器准备 查看,然后返回
  • 视图已建立
  • 过滤器关闭EntityManager并 将其从当前线程中解除绑定

您可以使用特殊过滤器在web视图中获取会话。添加到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>

JPA过滤器
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
JPA过滤器
/*
过滤器的工作原理如下:

@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
  • 过滤器拦截servlet请求
  • 过滤器打开EntityManager并将其绑定到当前线程
  • Web控制器被称为
  • Web控制器调用服务
  • 事务拦截器开始 新事务,检索线程绑定的EntityManager并绑定 它与交易有关
  • 服务被调用,使用 EntityManager,然后返回
  • 事务拦截器刷新 EntityManager然后提交事务
  • Web控制器准备 查看,然后返回
  • 视图已建立
  • 过滤器关闭EntityManager并 将其从当前线程中解除绑定

我只返回JSON。因此,问题不应该是试图延迟加载实体的web视图。错误发生在Controllers方法中。我将此用于带spring rest的JSON,工作起来很有魅力。它有一点性能过载(看我的描述),但应该可以工作。试试看:)真的很管用。我必须将@Transactional注释放在哪里?DAO还是控制器?我认为性能应该比总是获取急切的实体要好得多,你不这样认为吗?如果获取所有急切的实体,那么就不会,但是你可以使用其他获取方法,比如join-fetch。检查这个问题:我只返回JSON。因此,问题不应该是试图延迟加载实体的web视图。错误发生在Controllers方法中。我将此用于带spring rest的JSON,工作起来很有魅力。它有一点性能过载(看我的描述),但应该可以工作。试试看:)真的很管用。我必须将@Transactional注释放在哪里?DAO还是控制器?我认为性能应该比总是获取急切的实体要好得多,你不这样认为吗?如果获取所有急切的实体,那么就不会,但是你可以使用其他获取方法,比如join-fetch。检查此问题: