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
解决方法:
catch (HibernateException e) {
文章来源:http://blog.sina.com.cn/s/blog_67c92e8d0100izhc.html
参考:http://blog.youkuaiyun.com/mfhappy/article/details/7428924