Я использую spring + hibernate. Все мои HibernateDAO используют напрямую sessionFactory.
У меня есть уровень приложения -> уровень обслуживания -> уровень DAO, и все коллекции загружаются лениво.
Итак, проблема в том, что когда-то на уровне приложения (который содержит GUI / Swing) Я загружаю объект, используя метод уровня сервиса (который содержит аннотацию @Transactional), и я хочу использовать ленивое свойство этого объекта, но очевидно, что сеанс уже закрыт.
Как лучше всего решить эту проблему?
РЕДАКТИРОВАТЬ
Я пытаюсь использовать MethodInterceptor, моя идея - написать AroundAdvice для всех моих Entities и использовать аннотации, например:
// 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? Есть способ сделать это с помощью аннотации?