Hibernation session

I have a problem with hibernation and lazy loading.

Background: I have a Spring MVC web application, I use Hibernate for my persistence level. I use OpenSessionInViewFilter to allow me to create lazy load objects at my presentation level. And I am extending the HibernateDaoSupport classes and using HibernateTemplate to save / load objects. Everything works very well. Still.

Problem: I have a task that can be launched using a web request. When a request is sent to the controller, the controller will create a new Runnable for this task and start the thread to complete the task. Thus, the original thread will be returned, and the Hibernate session that was placed in ThreadLocal (OpenSessionInViewFilter) is not available for the new thread for the task. Therefore, when a task does some database stuff, I get the notorious LazyInitializationException.

Can anyone suggest a better way to make a Hibernate session available for a task?

Thanks for reading.

+5
source share
3 answers

Runnable a Spring bean @Transactional run. , , -.

, , , /.

+4

, Hibernate Runnable:

@Service
@Transactional
public class ScheduleService {

    @Autowired
    private SessionFactory      sessionFactory;

    @Autowired
    private ThreadPoolTaskScheduler     scheduler;

    public void doSomething() {

        ScheduledFuture sf = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(scheduler);
                final Session session = sessionFactory.openSession();
                // Now you can use the session
            }
        }, new CronTrigger("25 8 * * * *"));
    }
}

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext() Spring bean, . Spring bean .

+1

, - , ? Hibernates OpenSessionInViewFilter , , , , , , ( , HttpRequest). , .

, . , ?

0

All Articles