No Session Hibernate in @PostConstruct

我的未来我决定 提交于 2019-12-12 13:32:37

问题


MyDao class have the methods to do whole persistence tasks through Hibernate SessionFactory, it works fine.

I inject MyDao in MyService as can see above, but when @PostConstruct init() method is called after injected MyDao (debugging I can see MyDao well injected) get the next Hibernate exception:

org.hibernate.HibernateException: No Session found for current thread

My service implementation.

@Service("myService")
@Transactional(readOnly = true)
public class MyServiceImpl implements MyService {

    @Autowired
    private MyDao myDao;
    private CacheList cacheList;

    @PostConstruct
    public void init() {

        this.cacheList = new CacheList();
        this.cacheList.reloadCache(this.myDao.getAllFromServer());
    }

    ...
}

WAY TO SOLVE

As @Yogi recommended above to me, I have used TransactionTemplate to get one valid/active transaction session, in this case I have implemented throught constructor and works fine for me.

@Service("myService")
@Transactional(readOnly = true)
public class MyServiceImpl implements MyService {

    @Autowired
    private MyDao myDao;
    private CacheList cacheList;

    @Autowired
    public void MyServiceImpl(PlatformTransactionManager transactionManager) {

        this.cacheList = (CacheList) new TransactionTemplate(transactionManager).execute(new TransactionCallback(){

            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {

                CacheList cacheList = new CacheList();
                cacheList.reloadCache(MyServiceImpl.this.myDao.getAllFromServer());

                return cacheList;
            }

        });
    }

    ...
}

回答1:


I don't think there is any transaction allowed on @PostConstruct level so @Transactional won't do much here unless mode is set to aspectj in <tx:annotation-driven mode="aspectj" />.

As per this discussion you can use TransactionTemplate to start manual transaction inside init() to bind session but if you intend to strictly adhere to declarative transaction you need to use ApplicationListener to register event and user ContextRefreshedEvent to initiate transaction.




回答2:


Make sure you are running under transaction. I can see the transaction annotation but looks like you missed to activate the transaction management using annotation through the use of using <tx:annotation-driven/> tag in spring context.




回答3:


This happens because MyServiceImpl.init() is called by Spring after MyServiceImpl related bean construction and @Transaction annotation is not used to manage session lifecycle.
A solution might be consider Spring AOP around methods that use the cache instead of @PostConstruct



来源:https://stackoverflow.com/questions/22193562/no-session-hibernate-in-postconstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!