使用@Async注解是hibernate中抛出LazyInitializationExceptions

项目中有一个需求:批量产生一批数据,并存放在数据库中,并产生文件供下载。根据需求很容易想到@Async注解,但当注解加到service层的方法上时,却会抛出org.hibernate.LazyInitializationException。

项目使用spring3.1 和hibernate3.3.2GA,再经过各种谷歌之后终于找到原因,原因参考这里,具体是因为hibernate中session的范围问题。具体解决方法如下:

@Service
public class AsyncServiceImpl implements AsyncServiceInt{

@Autowired private SlowProcess slowProcess;

@Override
@Async
public void startSlowProcess(Integer scenarioId) {
    slowProcess.execute(param);
}

..

public class SlowProcess {

   @Transactional
   public double[] execute() { .. }

}

 此解决方法来自:http://stackoverflow.com/questions/17278385/spring-async-generates-lazyinitializationexceptions

猜你喜欢

转载自buxin-2008.iteye.com/blog/2136285