一、前言
通过hibernate定义HibernateUtil工具类,创建org.hibernate.SessionFactory会话工厂的操作会话对象org.hibernate.Session,并进行创建和修改POJO对象,详情代码示例说明。
二、代码示例import org.hibernate.Session;@b@import org.hibernate.SessionFactory;@b@import org.hibernate.cfg.AnnotationConfiguration; @b@import com.xwood.bean.Member;@b@@b@public class HibernateUtil {@b@@b@private static final SessionFactory sessionFactory = buildSessionFactory();@b@@b@private static SessionFactory buildSessionFactory() {@b@@b@try {@b@// Create the SessionFactory from hibernate.cfg.xml@b@return new AnnotationConfiguration().configure()@b@.buildSessionFactory();@b@} catch (Throwable ex) {@b@// Make sure you log the exception, as it might be swallowed@b@System.err.println("Initial SessionFactory creation failed." + ex);@b@throw new ExceptionInInitializerError(ex);@b@}@b@}@b@@b@public static SessionFactory getSessionFactory() {@b@return sessionFactory;@b@}@b@@b@public static void main(String[] args) {@b@Session session = HibernateUtil.getSessionFactory().getCurrentSession();@b@session.beginTransaction();@b@session.createQuery("from Member").setCacheable(true).list();@b@session.createQuery("from Member").setCacheable(true).list();;@b@session.getTransaction().commit();@b@@b@/*Session session2 = HibernateUtil.getSessionFactory()@b@.getCurrentSession();@b@session2.beginTransaction();@b@Member member2 = (Member) session2.get(Member.class, 20);@b@member2.setClass_("2");@b@session2.getTransaction().commit();@b@System.out.println(session == session2);*/@b@}@b@}