I have a spring-hibernate code which does the following two steps
1. Save an Object to database
2. Retrieve the object saved and display the details of that values saved
To do the above two steps in a row , I saved the getHibernateTemplate().saveOrUpdate(obj);. To my knowledge this calls the hibernate saveorupdate() method internally and saves it to the database. After saving to the database it closes the Hibernate session.
In step two, to retrieve the object from the database, I executed return (Employee)getHibernateTemplate().load(Employee.cla ss, id);. To retrieve data from database the earlier session is closed, now it says, org.hibernate.LazyInitializationException: could not initialize proxy - no Session
To avoid the above situation, I placed both the statements in a single method and declared it as a transaction (@Transactional(propagation=Propagation.REQUIRED , rollbackFor=Exception.class). Still the same issue. I am pasting my code below, please kindly look into it. Thanks in advance.
Bean retrived from bean factory ...
Data has been saved
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Use of Hibernate template is not recommended. You should inject Hibernate session factory in you DAO & get Hibernate session by calling the getCurrentSession() method on session factory. This will get current session or create new session depending on transaction settings.
Can you share spring configuration file, you current issue could be caused by incorrect transaction configurations.
Except for HibernateTemplate, which I agree shouldn't be used with the current versions of Hibernate. But I don't see any other Spring. So that one method in your main class has @Transactional. But in order for it to be transactional it would have to be defined as a Spring bean in the configuration, which I don't think you want to put the class that has your public static void main as a Spring bean.
Can you post your Spring-Hibernate.xml file.
Also, if you are just learning Spring, I highly recommend using the latest version to learn from. Based on the code I see in your main method, you are using the older style of Spring, mostly from Spring 1.x days. We are at Spring 3.x today.