2013-03-20 56 views
2

我知道冬眠很好,相当弹簧芯集成,我可以使用Hibernate模板和休眠DAO支持类都集成,但是从休眠3.1我们已经上下文session,即我们需要的不是使用Hibernate模板和休眠DAO支持,但是当我试图用这个概念整合和注入SessionFactory的在我的DAO类所有的事都写,但我想插入数据休眠显示插入查询,但数据不会保存到数据库,请帮助我,我能做些什么。 这里是我的代码春3.0和Hibernate 3.5上下文session

@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(); 
+0

任何一个可以建议最好的网站,了解关于Spring – 2014-04-26 11:35:16

回答

0

有几个问题与您的代码,

  1. DAO已经交易,管理由春天。你正在开始另一项交易。
  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); 
+0

我是一个新手使用春天,但我的故障知道冬眠可以请你建议我最好的资源学习春天 – 2014-04-26 11:36:37