当前位置: 代码迷 >> Java Web开发 >> Hibernate的有关问题,配置好了,但是不能真正实现删除操作
  详细解决方案

Hibernate的有关问题,配置好了,但是不能真正实现删除操作

热度:26   发布时间:2016-04-17 15:09:32.0
Hibernate的问题,配置好了,但是不能真正实现删除操作!
HibernateUtil的代码:
package   com.studorm.dao;

import   org.hibernate.HibernateException;
import   org.hibernate.Session;
import   org.hibernate.SessionFactory;
import   org.hibernate.Transaction;
import   org.hibernate.cfg.Configuration;

public   class   HibernateUtil   {
private   static   final   SessionFactory   sessionFactory;

static   {
try   {
//   Create   the   SessionFactory
sessionFactory   =   new   Configuration().configure()
.buildSessionFactory();
}   catch   (Throwable   ex)   {
ex.printStackTrace();
System.out.println( "Initial   SessionFactory   creation   failed. ");
throw   new   ExceptionInInitializerError(ex);
}
}

public   static   final   ThreadLocal   tLocalsess   =   new   ThreadLocal();

public   static   final   ThreadLocal   tLocaltx   =   new   ThreadLocal();

/*
  *   getting   the   thread-safe   session   for   using
  */
public   static   Session   currentSession()   {
Session   session   =   (Session)   tLocalsess.get();

//   open   a   new   one,   if   none   can   be   found.
try   {
if   (session   ==   null   ||   !session.isOpen())   {
session   =   openSession();
tLocalsess.set(session);
}
}   catch   (HibernateException   e)   {
//   throw   new   HibernateException(e);
e.printStackTrace();
}
return   session;
}

/*
  *   closing   the   thread-safe   session
  */
public   static   void   closeSession()   {

Session   session   =   (Session)   tLocalsess.get();
try   {
if   (session!=   null   &&   session.isOpen())   {
session.close();
}
tLocalsess.set(null);
}   catch   (HibernateException   e)   {
//   throw   new   InfrastructureException(e);
}
}

/*
  *   begin   the   transaction
  */
public   static   void   beginTransaction()   {
System.out.println( "begin   tx ");
Transaction   tx   =   (Transaction)   tLocaltx.get();
try   {
if   (tx   ==   null)   {
tx   =   currentSession().beginTransaction();
tLocaltx.set(tx);
System.out.println( "Tx   is   End! ");
}
}   catch   (HibernateException   e)   {
//   throw   new   InfrastructureException(e);
}
}

/*
  *   close   the   transaction
  */
public   static   void   commitTransaction()   {
Transaction   tx   =   (Transaction)   tLocaltx.get();
try   {
if   (tx   !=   null   &&   !tx.wasCommitted()   &&   !tx.wasRolledBack())
tx.commit();
System.out.println( "commit   tx ");
tLocaltx.set(null);
}   catch   (HibernateException   e)   {
  相关解决方案