用hibernate插一些数据,但是只能一个一个插,一起插到时候,第一个数据是成功插入的,从第二个开始就不能成功插入,报的是:Transaction not successfully started
  HibernateUtil类是这样写的:
  public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
static{
try {
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
Session session=threadLocal.get();
if(session==null||!session.isOpen()){
session=(sessionFactory!=null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void closeSession(){
Session session=(Session)threadLocal.get();
threadLocal.set(null);
if(session!=null){
session.close();
}
}
   业务逻辑层管理事务:
     public class TypeBizImpl implements TypeBiz{
private BaseDAO tDAO=new TypeDAO();
private Transaction tx=HibernateUtil.getSession().beginTransaction();
@Override
public void addType(Filmtype type) {
// TODO Auto-generated method stub
try {
tDAO.add(type);
tx.commit();
} catch (Exception e) {
// TODO: handle exception
tx.rollback();
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
不知道哪里错了

解决方案 »

  1.   

    private Transaction tx=HibernateUtil.getSession().beginTransaction();
    @Override
    public void addType(Filmtype type) {
    // TODO Auto-generated method stub
    try {
    tDAO.add(type);
    tx.commit();
    } catch (Exception e) {
    // TODO: handle exception
    tx.rollback();
    e.printStackTrace();
    }finally{
    HibernateUtil.closeSession();
    }
    改成private Transaction tx=null;
    @Override
    public void addType(Filmtype type) {
    // TODO Auto-generated method stub
    HibernateUtil.getSession().beginTransaction();try {
    tDAO.add(type);
    tx.commit();
    } catch (Exception e) {
    // TODO: handle exception
    tx.rollback();
    e.printStackTrace();
    }finally{
    HibernateUtil.closeSession();
    }
      

  2.   

    错了private Transaction tx=null;
    @Override
    public void addType(Filmtype type) {
    // TODO Auto-generated method stub
    tx= HibernateUtil.getSession().beginTransaction();try {
    tDAO.add(type);
    tx.commit();
    } catch (Exception e) {
    // TODO: handle exception
    tx.rollback();
    e.printStackTrace();
    }finally{
    HibernateUtil.closeSession();
    }
     因为每个Transaction 提交后要重新 开始才有用