2

我非常了解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();
4

1 回答 1

0

你的代码有几个问题,

  1. DAO 已经是事务性的,由 Spring 管理。您正在 main 中开始另一笔交易。
  2. 您正在打开会话两次。一次在主,另一次在道。
  3. 当您使用上下文会话时,最好调用 sessionFactory.getCurrentSession()

现在如果你用 Spring 正确配置了事务管理器,下面的代码就可以工作了,我只是添加了一些注释,看看它是否对你有帮助:)

@Transactional
 public class UserDAO {

SessionFactory sessionFactory;

public void save(User transientInstance) {
   //Removed try-catch. It was just catching RuntimeException only to re throw it
   sessionFactory.openSession().save(transientInstance);

}
//I would get rid of this method.  
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
    return (UserDAO) ctx.getBean("UserDAO");
}
//I would get rid of this method or make it private  
public SessionFactory getSessionFactory() {
    return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
}

主要代码

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//I would use builder instead of constructor here
User user=new User("firstName", "lastName", "address", "phoneNo", "mobileNo", "email", "password", false, null);

UserDAO ud=(UserDAO)context.getBean("UserDAO");
ud.save(user); 
于 2013-03-20T17:12:32.763 回答