最近在做SSH的时候,发现hibernate4已经取消了HibernateTemplate,那么通过spring3.1获取Session的时候是需要获取到SessionFactory,然后再通过getcurrentsession()来获取session吗?获取的session还需要开启事务和关闭吗,感觉好麻烦如果这样做
        还是说可以直接使用sessionFactory.getCurrentSession().save(user),而不必再new一个session出来,spring会自动帮助关闭session吗?

解决方案 »

  1.   

    目前代码是这样写的,新手,
    public class UserDAOImpl implements UserDAO{

    private SessionFactory sessionFactory; @Override
    public boolean add(User user)throws Exception{
    sessionFactory.getCurrentSession().save(user);
    return true;


    @Override
    public boolean exists(String name) throws Exception{

    long count = (Long)sessionFactory.getCurrentSession().createQuery("select count(*) from User u where u.name = :name")
    .setString("name", name)
    .uniqueResult();
    if(count > 0) return true;
    return false;
    } public SessionFactory getSessionFactory() {
    return sessionFactory;
    }

    @Resource(name="sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
    }

    }
      

  2.   

    需要配置并启动事务,在spring配置文件中加入事务配置,可能是这样:
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    在类上加入这个注解:
    @Transactional
    public class UserDAOImpl implements UserDAO{
    .....
    这样就可以直接更新数据了:
    sessionFactory.getCurrentSession().save(user);
    spring将负责对session和事务的管理,用户不需要管理session和事务。
      

  3.   

    另springSessionContext是怎么回事,是不是springSessionContext.currentSession也可以拿到session,我实验的时候拿到的一直是空值<bean id="springSessionContext" class="org.springframework.orm.hibernate4.SpringSessionContext">
         <property name="sessionFactory" ref="sessionFactory"></property>
         </bean>
      

  4.   

    hibernate你最好自己关闭session
    和spring是没关系的