【发布时间】:2011-05-11 14:05:09
【问题描述】:
我正在使用 spring + hibernate。我所有的 HibernateDAO 都直接使用 sessionFactory。
我有应用层 -> 服务层 -> DAO 层,所有集合都是延迟加载的。
所以,问题是有时在应用程序层(包含 GUI/swing)中,我使用服务层方法(包含 @Transactional 注释)加载实体,并且我想使用该对象的惰性属性,但是显然会话已经关闭。
解决这个问题的最佳方法是什么?
编辑
我尝试使用MethodInterceptor,我的想法是为我所有的实体写一个AroundAdvice并使用注释,例如:
// Custom annotation, say that session is required for this method
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SessionRequired {
// An AroundAdvice to intercept method calls
public class SessionInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation mi) throws Throwable {
bool sessionRequired=mi.getMethod().isAnnotationPresent(SessionRequired.class);
// Begin and commit session only if @SessionRequired
if(sessionRequired){
// begin transaction here
}
Object ret=mi.proceed();
if(sessionRequired){
// commit transaction here
}
return ret;
}
}
// An example of entity
@Entity
public class Customer implements Serializable {
@Id
Long id;
@OneToMany
List<Order> orders; // this is a lazy collection
@SessionRequired
public List<Order> getOrders(){
return orders;
}
}
// And finally in application layer...
public void foo(){
// Load customer by id, getCustomer is annotated with @Transactional
// this is a lazy load
Customer customer=customerService.getCustomer(1);
// Get orders, my interceptor open and close the session for me... i hope...
List<Order> orders=customer.getOrders();
// Finally use the orders
}
你认为这行得通吗? 问题是,如何在 xml 文件中为我的所有实体注册此拦截器? 有没有办法通过注释来做到这一点?
【问题讨论】:
标签: java hibernate spring lazy-loading