Search code examples
springhibernatelazy-initialization

Invoking proxied DAO methods from Spring stand alone client :- could not initialize proxy - no Session


I have a third party jar in my class path which has some services and DAO's developed on top of Spring 2.0.6 and Hibernate3.2.6. I need to call some of the services and daos.

Using ClassPathXmlApplicationContext I'm able to load the application context and able to access the services and daos. Both the service and dao are following ProxyFactoryBean pattern.

Problem comes when I'm accessing a DAO which has some single valued associations.When I'm accessing associated entity I'm getting lazy initialization problem.

To solve this problem:- If it is in my own application JAR I'll be able to change the fetch type into join or in DAOImpl method I could use Hibernate.initialize().

Is there a way to avoid this problem from the stand alone code itself? Or any other way to solve this issue without modifying applicationContext.xml and DAOImpl


Solution

  • You need to put the caller method into one single transaction.

    If you have Spring transactional environment, you can put the call of the DAO services/repositories in your own service/method which is marked as @Transactional, or if transaction support is not enabled, but you still have spring support in your application, you can just use TransactionTemplate directly, provided by spring

    @Autowire 
    private PlatformTransactionManager txManager; 
    
    TransactionTemplate template  = new TransactionTemplate(this.txManager); 
    template.execute( new TransactionCallback<Object>(){ 
      public void doInTransaction(TransactionStatus status){ 
       // work done here will be wrapped by a transaction and committed. 
       // status.setRollbackOnly(true) is called or an exception is thrown 
      } 
    });
    

    Otherwise you have manually handle transactionality by your own , depending on the technologies your app is using.