openSession()和getCurrentSession()有什么不同?
利用Hibernate进行记录插入的代码:流行的主流写法和Hibernate官方文档里的写法哪个更好?

解决方案 »

  1.   

    openSession:直接创建session。。不管当前程序内 有没有。
    getCurrentSession先找池内有没有 有 就用 没有 在创建。。getCurrentSession 
    主流写法 交给orm层来管理 eg: hibernate 中 继承 hibernateSupport 用this.getHiberanteTempelte
    得到session比较好了..
      

  2.   

    我看到过的一种写法:
                    Configuration cfg = new AnnotationConfiguration();
    SessionFactory sf = cfg.configure().buildSessionFactory();
    Session session = sf.getCurrentSession();
    session.beginTransaction();
    session.save(t);
    session.getTransaction().commit();
    session.close();
    sf.close();官方的好像比较复杂(我没有修改过):
    package org.hibernate.tutorial.util;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    public class HibernateUtil {
               private static final SessionFactory sessionFactory = buildSessionFactory();
               private static SessionFactory buildSessionFactory() {
                           try {
                           // Create the SessionFactory from hibernate.cfg.xml
                           return new Configuration().configure().buildSessionFactory();
                           }
                           catch (Throwable ex) {
                           // Make sure you log the exception, as it might be swallowed
                           System.err.println("Initial SessionFactory creation failed." + ex);
                           throw new ExceptionInInitializerError(ex);
                            }
               }
               public static SessionFactory getSessionFactory() {
                          return sessionFactory;
               }
    }
    package org.hibernate.tutorial;
    import org.hibernate.Session;
    import java.util.*;
    import org.hibernate.tutorial.domain.Event;
    import org.hibernate.tutorial.util.HibernateUtil;
    public class EventManager {
               public static void main(String[] args) {
                         EventManager mgr = new EventManager();
                         if (args[0].equals("store")) {
                                      mgr.createAndStoreEvent("My Event", new Date());
                                      }
                         HibernateUtil.getSessionFactory().close();
                         }
                         private void createAndStoreEvent(String title, Date theDate) {
                         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                         session.beginTransaction();
                         Event theEvent = new Event();
                         theEvent.setTitle(title);
                         theEvent.setDate(theDate);
                         session.save(theEvent);
                         session.getTransaction().commit();
                 }
    }
      

  3.   

    这两种写法其实是一样的,管方的比较完善而已.
    管方的是把sessionFactory放在静态区域内.这样不管用多少次都只需建一个.