……
我在classA中强行调用了session.flush()就可以了,晕
不是说调用session.close()方法会自动调用.flush()方法的嘛

解决方案 »

  1.   

    现在还有个问题,比较麻烦的
    设想有个classC 本身有事务的代码,同时调用classB中的方法,但是classB中已经有了事务,有什么办法可以让这两个事物统一起来,类似于EJB中使用的容器事务?
      

  2.   

    public class HibernateSessionFactory { private static SessionFactory sessionFactory;   //这里使用static
    private static final ThreadLocal session = new ThreadLocal(); //这里使用static
    private static final ThreadLocal threadTransaction = new ThreadLocal(); //这里使用static,可以共享Transaction //获取session
    public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
    try {
    sessionFactory =
    new Configuration().configure().buildSessionFactory();
    } catch (HibernateException ex) {
    throw new RuntimeException(
    "Exception building SessionFactory: " + ex.getMessage(),
    ex);
    }
    }
    return sessionFactory;
    } public static void init() throws HibernateException {
    if (sessionFactory == null ) {
    sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    } //创建session
    public static Session currentSession() throws HibernateException {
    Session s = (Session) session.get();
    if (s == null) {
    init();
    s = sessionFactory.openSession();
    session.set(s);
    }
    return s;
    } //关闭session
    public static void closeSession() throws HibernateException {
    Session s = (Session) session.get();
    session.set(null);
    if (s != null)
    s.close();
    } //开始事务
    public static void beginTransaction() throws HibernateException {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    if (tx == null) {
    tx = currentSession().beginTransaction();
    threadTransaction.set(tx);
    }
    } catch (HibernateException e) {
    throw e;
    }
    } //回滚事务
    public static void rollbackTransaction() throws HibernateException {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    threadTransaction.set(null);
    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
    tx.rollback();
    }
    } catch (HibernateException e) {
    throw e;
    } finally {
    closeSession();
    }
    } //结束事务
    public static void commitTransaction() throws HibernateException {
    Transaction tx = (Transaction) threadTransaction.get();
    try {
    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
    tx.commit();
    }
    threadTransaction.set(null);
    } catch (HibernateException e) {
    rollbackTransaction();
    throw e;
    }
    } //重置
    public static void release() throws HibernateException {
    Session s = (Session) session.get(); if (null == s)
    return;
    else {
    session.set(null);
    s.flush();
    if (s.isOpen())
    s.close();
    }
    }}使用Spring里的事务处理,可以很完美的把事务处理交给业务层,而又不会和业务层偶合在一起
      

  3.   

    呵呵,我自己想了个办法,由最外层的javaBean管理事务,中间调用的bean或者方法由最外层的bean来通知是否要起事务,效果还行,谢谢大家。