2

私は休止状態をよく知っており、かなりSpringコアです。休止状態のテンプレートと休止状態のDAOサポートクラスを使用して両方を統合できますが、休止状態3.1以降、コンテキストセッションがあります。つまり、休止状態のテンプレートと休止状態の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 によって管理されています。メインで別のトランザクションを開始しています。
  2. セッションを 2 回開いています。1 回は main で、もう 1 回は dao で。
  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 に答える