小弟新手,最近在学习Hibernate,在如何使用事务上碰到一个问题。
想知道大家都是如何取得Session和处理事务的!(不使用Spring).
是把开Session和事务放在DAO中还是放在业务逻辑层。开Session放在业务逻辑层好像挺麻烦,要把Session做为参数传到DAO中去。如果是在DAO中开Session,那业务逻辑层又如何控制事务。实在想不到什么好办法。跪求高手解惑。详细说明请参考: http://www.javapknet.com/htmlhelp/2009090/01674e8295f4db99.html

解决方案 »

  1.   

    J2EE 设计模式之事务上下文
      

  2.   

    这里有一定的介绍:http://www.javaresearch.org/article/59935.htm详尽的介绍需要看这本书:
      

  3.   

    原理就是通过动态代理将业务逻辑进行代理在代理方法中获得 Session 或者是 Connection,并进行事务处理。将获得的连接对象放在 ThreadLocal 对象中。同时需要更改 DAO 中连接获得的方式,应从 ThreadLocal 中取出,并且在 DAO 中连接对象不能关闭。
      

  4.   

    修改HibernateSessionFactory的getSession()方法,使每个session关联到当前线程。则在一个线程内,通过HibernateSessionFactory.getSession()得到的Session都是同一个session.只要是同一个sesion, 则在什么地方申明事务边界都可以.以下代码是myelipse自动生成的.public class HibernateSessionFactory {
    private static String CONFIG_FILE_LOCATION = "/dao/hibernate/Hibernate.cfg.xml";
    private static final ThreadLocal threadLocal = new ThreadLocal();
    private static final Configuration cfg = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    public static Session currentSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
    try {
    cfg.configure(CONFIG_FILE_LOCATION);
    sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
    System.err.println("%%%%   Error   Creating   SessionFactory   %%%%");
    e.printStackTrace();
    }
    }
    session = (sessionFactory != null) ? sessionFactory.openSession() : null;
    threadLocal.set(session);
    }
    return session;
    }
    public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    threadLocal.set(null);
    if (session != null) {
    session.close();
    }
    }
    private HibernateSessionFactory() {
    }}
      

  5.   

    如果想像ejb那樣,如果存在一個事務就用这个事务,如果不存在就开启一个新事务。该如何做。