ansaction not successfully started 处理办法

来源:互联网 发布:马克安东尼 知乎 编辑:程序博客网 时间:2024/06/05 04:38
Transaction not successfully started 处理办法 


代码如下

public User valid(String username, String password)
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=? and password=?");
query.setString(0, username.trim());
query.setString(1, password.trim());

user = (User) query.uniqueResult();

query = null;

tx.commit();

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



Exception in thread "main" org.hibernate.TransactionException: Transaction not successfully started
at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:149)
at com.hibernate.dao.UserDAO.valid(UserDAO.java:38)
at com.hibernate.dao.UserDAO.main(UserDAO.java:104)

分析原因:个人认为应该讲if()部分代码放在catch()块中在throw之前。因为抛出异常后就不应该再有其他语句。所以将红色部分代码修改为:



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

HibernateSessionFactory.closeSession();
}



下面为修改后的运行结果:

Hibernate: select user0_.id as id0_, user0_.username as username0_, user0_.password as password0_, user0_.email as email0_ from user user0_ where user0_.username=?
false
Hibernate: select user0_.id as id0_, user0_.username as username0_, user0_.password as password0_, user0_.email as email0_ from user user0_ where user0_.username=?
false
Hibernate: insert into user (username, password, email) values (?, ?, ?)
true
显然修改后异常没有了,编译顺利通过,也得到了想要的效果
原创粉丝点击