The old version of my code:
Session session = sessionFactory.openSession();
Query query = session.createQuery("From User");
List<Users> users = query.list();
session.close();
I config the hibernate.cfg.xml file:
<property name="hibernate.current_session_context_class" > thread</property >
context.xml
<tx:annotation-driven transaction-manager="transactionManager"/>
Current code:
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("From User");
List<Users> list = query.list();
tx.commit();
I have to add Transaction code, or I will get an error
org.hibernate.HibernateException: createQuery is not valid without active transaction
What am I missing for the config?
ApplicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?>
......
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<context:annotation-config />
<context:component-scan base-package="*" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
public class IndexController {
@Autowired
UserService users;
@RequestMapping("/index")
public String index(ModelMap model ) {
User user= users.test();
model.put("user", user);
return "index";
}