设为首页 加入收藏

TOP

hibernate入门配置
2014-11-23 22:16:41 】 浏览:404
Tags:hibernate 入门 配置

  HibernateUtil.java


  package com.netease.wireless.groupsms.hbnt.util;


  import net.sf.hibernate.HibernateException;


  import net.sf.hibernate.Session;


  import net.sf.hibernate.cfg.Configuration;


  /**


  * Configures and provides access to Hibernate sessions, tied to the


  * current thread of execution. Follows the Thread Local Session


  * pattern, see {@link http://hibernate.org/42.html}.


  */


  public class HibernateUtil {


  /**


  * Location of hibernate.cfg.xml file.


  * NOTICE: Location should be on the classpath as Hibernate uses


  * #resourceAsStream style lookup for its configuration file. That


  * is place the config file in a Java package - the default location


  * is the default Java package.


  * Examples:


  * CONFIG_FILE_LOCATION = "/hibernate.conf.xml".


  * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".


  */


  private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";//hibernate.cfg.xml


  /** Holds a single instance of Session */


  private static final ThreadLocal threadLocal = new ThreadLocal();


  /** The single instance of hibernate configuration */


  private static final Configuration cfg = new Configuration();


  /** The single instance of hibernate SessionFactory */


  private static net.sf.hibernate.SessionFactory sessionFactory;


  /**


  * Returns the ThreadLocal Session instance. Lazy initialize


  * the SessionFactory if needed.


  *


  * @return Session


  * @throws HibernateException


  */


  public static Session currentSession() throws HibernateException {


  Session session = (Session) threadLocal.get();


    if (session == null) {


  if (sessionFactory == null) {


  try {


  cfg.configure(CONFIG_FILE_LOCATION);


  //cfg.configure();


  sessionFactory = cfg.buildSessionFactory();


  }


  catch (Exception e) {


  System.err.println("%%%% Error Creating SessionFactory %%%%");


  System.err.println("|||||||||||||" + e.getMessage());


  e.printStackTrace();


  }


  }


  session = sessionFactory.openSession();


  threadLocal.set(session);


  }


  return session;


  }


  /**


  * Close the single hibernate session instance.


  *


  * @throws HibernateException


  */


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇JavaScript实现Web打印 下一篇根据批量URL生成有书签的PDF文档..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目