Reputation: 4504
I am using Hibernate3 with Spring 3. I am trying to start hibernate transaction using Spring. Given below is my configurations
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
I am getting the following error while running the application.
HibernateException: get is not valid without active transaction
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:341)
I have the following line in hibernate config xml
<property name="hibernate.current_session_context_class">thread</property>
The code which uses hibernate transaction is:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Book book = (Book)session.get(Book.class, id);
What could be wrong in this? Is the value for current_session_context_class is anything other than thread?
Upvotes: 1
Views: 2895
Reputation: 4504
The problem was in the line
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
It seems, When you are using Spring transaction management, you need to use the sessionFactory which you configured in the applicationContext.xml (using dependency injection).
Following piece of code solved the problem.
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
In the applicationContext.xml:
<bean id="BookService" class="hibernate.BookServiceImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Upvotes: 2