我非常了解hibernate,并且相当了解Spring核心,我可以使用hibernate模板和hibernate dao支持类来集成两者但是从hibernate 3.1开始我们有上下文会话,即我们不需要使用hibernate模板和hibernate dao支持但是当我试图与这个概念集成并在我的 dao 类中注入 sessionFactory 一切都会写,但我正在尝试插入数据休眠显示插入查询但数据未保存到数据库请帮助我我能做什么。这是我的代码
@Transactional
public class UserDAO {
SessionFactory sessionFactory;
public void save(User transientInstance) {
try {
sessionFactory.openSession().save(transientInstance);
} catch (RuntimeException re) {
throw re;
}
}
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
这是我的 beans.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<bean id="UserDAO" class="dao.UserDAO">
<property name="sessionFactory"><ref bean="sessionFactory" /></property>
</bean>
这是我的主要代码
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=new User("firstName", "lastName", "address", "phoneNo", "mobileNo", "email", "password", false, null);
SessionFactory factory=(SessionFactory)context.getBean("sessionFactory");
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
UserDAO ud=(UserDAO)context.getBean("UserDAO");
ud.save(user);
tx.commit();
session.close();