2013-03-20 20 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