MyException - 我的异常网
当前位置:我的异常网» Java Web开发 » hibernate无法往数据库添加记录,但能查询,该如何处理

hibernate无法往数据库添加记录,但能查询,该如何处理(2)

www.MyException.Cn  网友分享于:2013-01-20  浏览:20次

  }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();



@SuppressWarnings("unchecked")
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;
  }


   
@SuppressWarnings("unchecked")
public static void closeSession() {

  Session session = (Session) tLocalsess.get();
  tLocalsess.set(null);
  try {
  if (session != null && session.isOpen()) {
  session.close();  
  }

  } catch (HibernateException e) {
  // throw new InfrastructureException(e);
  }
  }




@SuppressWarnings("unchecked")
public static void beginTransaction() {
  System.out.println("begin Transaction");
  Transaction tx = (Transaction) tLocaltx.get();
  try {
  if (tx == null) {
  tx = currentSession().beginTransaction();
  tLocaltx.set(tx);
  }
  } catch (HibernateException e) {
  // throw new InfrastructureException(e);
  }
  }

  


@SuppressWarnings("unchecked")
public static void commitTransaction() {
  Transaction tx = (Transaction) tLocaltx.get();
  try {  
  if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
  tx.commit();
  tLocaltx.set(null);
  System.out.println("commit tx");
  } catch (HibernateException e) {
  // throw new InfrastructureException(e);
  }
  }

 
   
@SuppressWarnings("unchecked")
public static void rollbackTransaction() {
  Transaction tx = (Transaction) tLocaltx.get();
  try {
  tLocaltx.set(null);
  if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
  tx.rollback();
  }
  } catch (HibernateException e) {
  // throw new InfrastructureException(e);

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有