Transaction not successfully started 处理办法

来源:互联网 发布:linux 添加path 编辑:程序博客网 时间:2024/06/04 19:04
package com.demo.hibernate.dao;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import com.demo.hibernate.beans.User;import com.demo.hibernate.util.HibernateSessionFactory;public class UserDAO {public User getUser(String username) throws HibernateException{Session session = null;Transaction tx = null;User user = null;try{session = HibernateSessionFactory.currentSession();tx = session.beginTransaction();Query query = session.createQuery("from User where username=?");query.setString(0, username.trim());user = (User)query.uniqueResult();query = null;tx.commit();}catch(HibernateException e){if(tx!=null){tx.rollback();}throw e;}finally{HibernateSessionFactory.closeSession();}return user;}}

控制台出现报错

Exception in thread "main" org.hibernate.TransactionException: Transaction not successfully started
 at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:149)


解决方法:

catch (HibernateException e) {
   if (tx != null) {
    tx.rollback();
   }
   throw e;
  } finally {
   
   HibernateSessionFactory.closeSession();
  }

文章来源:http://blog.sina.com.cn/s/blog_67c92e8d0100izhc.html

参考:http://blog.csdn.net/mfhappy/article/details/7428924