问题描述
|
我怎样才能得到一个懒惰的对象?
例如,
我有一个\“ customer \”表和\“ request \”表,然后使用hibernate和JPA构建了一个项目。
客户表中有这样的代码
@OnetoMany(cascade = CascadeType.ALL,fetch =FetchType.LAZY,mappedBy = \"customer\")
public Set<Request> getRequests() {
return this.requests;
}
因此,如果从客户对象调用getRequests()
方法,则由于它是惰性的,它将返回一个空对象。
如何在不使用EAGER
批注的情况下使懒惰对象充满?
我已经看到我的问题取决于会话,因为会话已经结束。因此,在服务器端,我需要通过JPA保持打开会话。
我该怎么做?
这是我的applicationContext.xml的一部分,但是不起作用:
<bean class=\"org.springframework.orm.jpa.LocalEntityManagerfactorybean\" id=\"entityManagerFactory\">
<property name=\"persistenceUnitName\" value=\"gestazPU\"/>
</bean>
<bean class=\"org.springframework.orm.jpa.JpaTransactionManager\" id=\"transactionManager\">
<property name=\"entityManagerFactory\" ref=\"entityManagerFactory\"/>
</bean>
<bean class=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" />
<bean id=\"ebOpenEMinView\" class=\"org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor\">
<property name=\"entityManagerFactory\" ref=\"entityManagerFactory\"/>
</bean>
<tx:annotation-driven proxy-target-class=\"true\" transaction-manager=\"transactionManager\"/>
<bean id=\"TipoTicketDAO\" class=\"it.stasbranger.gestaz.server.dao.impl.TipoTicketDAOImpl\">
<property name=\"entityManagerFactory\" ref=\"entityManagerFactory\" />
</bean>
解决方法
使用
Hibernate.initialize(lazyCollection)
-如果当前会话处于活动状态,则将初始化集合。
, 我只能假设您有此问题,因为您正在尝试访问独立实体中的延迟加载字段,对吗?否则,JPA提供程序将自动为您加载。
仅使用JPA东西(不提供依赖于提供程序的功能),我可以想到两个选择:
1)您将获取类型更改为渴望。由于您似乎需要在一个分离的实体中收集该集合,因此最好是在分离之前确保其已完全加载。
2)在分离实体之前,请确保已加载集合。您可以在分离实体之前简单地在托管实体中调用getRequests()方法,这可以通过强制提供程序(如果尚未加载)来加载它。
对于第二种选择,您可以使用PersistenceUtil.isLoaded()方法确定是否加载了集合,并根据状态确定是否强制加载延迟获取集合。
, 您可能需要entityManager,或者如果它是一个Web应用程序,则可以通过“在视图中打开会话”来保持会话打开,并在需要时延迟获取对象。
, 循环设置,调用getId()或对象的任何方法。这必须在会话关闭之前完成,这意味着在事务内部。
休眠独立版
public Customer getCustomerWithRequest(Integer customerId){
Session session = HibernateUtil.startTransaction();
Customer = (Customer) session.get(Customer.class,customerId);
List<Request> requests = customer.getRequests();
for(Request rq:requests){
rq.getId();
}
session.close();
return customer;
}
Spring / Hibernate | JPA版本
@Transaction
public Customer getCustomerWithRequest(Integer customerId){
//get the requests and loop in here like above
}