spring中使用事务,必须在spring配置文件中正确的配置申明事务或者在web.xml文件中配置OpenSessionInViewFilter,这样才能保证每个线程都有绑定的session,这样才能进行事务操作。否则,出现异常。

解决方案 »

  1.   

    static SessionFactory factory=HibernateUtil.getSessionFactory();
    //判断传的用户名和密码是否存在,并返回查到的记录数
    public long login(String user,String pass){
    Session session=factory.getCurrentSession();
    Transaction trans=session.beginTransaction();
    Query query=session.createQuery("select count(name) from Users where name=:name and password=:pass");
    query.setParameter("name", user);
    query.setParameter("pass", pass);
    long num=(Long)query.uniqueResult();
    trans.commit();
    factory.close();
    return num;
    }
    代码就是这样,它就报我Transaction trans=session.beginTransaction();这样一行有错误
      

  2.   

     使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
      * 如果采用jdbc独立引用程序配置如下:
        <property name="hibernate.current_session_context_class">thread</property>
      * 如果采用了JTA事务配置如下  
        <property name="hibernate.current_session_context_class">jta</property>
      

  3.   

     <property name="hibernate.current_session_context_class">thread</property>这条我配了的