hiberante 学习体会

下面是小弟学习Hibernate 的一些体会:

 

package com.wosdman.test;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.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 HibernateSessionFactory {

 

    /**

     * Location of hibernate.cfg.xml file.

     * Location should be on the classpath as Hibernate uses 

     * #resourceAsStream style lookup for its configuration file.

     * The default classpath location of the hibernate config file is

     * in the default package. Use #setConfigFile() to update

     * the location of the configuration file for the current session.  

      */

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

       private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    private  static Configuration configuration = new Configuration();

    private static org.hibernate.SessionFactory sessionFactory;

    private static String configFile = CONFIG_FILE_LOCATION;

 

       static {

           try {

                     configuration.configure(configFile);

                     sessionFactory = configuration.buildSessionFactory();

              } catch (Exception e) {

                     System.err

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

                     e.printStackTrace();

              }

    }

    private HibernateSessionFactory() {

    }

      

       /**

     * Returns the ThreadLocal Session instance.  Lazy initialize

     * the <code>SessionFactory</code> if needed.

     *

     *  @return Session

     *  @throws HibernateException

     */

public static Session getSession() throws HibernateException {

 

首选对 ThreadLocal 作一个简单的说明 : 它的出现是为更好的服务的多线程 , 使基多线程的应用程序更加完美 . 如果有这样一种需要 : 每当我们开起一个新的线程 , 都需要访问一个变量 , 但这个变量可能会在其它的线程中被改变 , 这时 ThreadLocal 最有效来解这个问题 .

其实 ThreadLocal 并不是一个 Thread 而是一个 Thread local var , 我觉得应该访问的是本地的私有的静态的 (private static) 变量 , 但下面的这个应用不是的 ,session 并不是 private static

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

              当每一次调用时 ,sessionnull

              if (session == null || !session.isOpen()) {

                     if (sessionFactory == null) {  // 似乎没有必要 , 因为在前面的 static 代码块中就对它 sessionfactory 初始化了

                            rebuildSessionFactory(); // 多重判断后来构建一个 sessionfactory, 其实是再次调用 configruationbuildsessionfactory() method 完成的

                     }

                     session = (sessionFactory != null) ? sessionFactory.openSession()

                                   : null;    // 经过上面的判断以后 , 其实我觉得 sessionfactory 不可能为 null, 为了安全起见 , 与程序的逻辑性,这样写真有必要的 ,

来构建一个 session 对象

                     threadLocal.set(session);    // 把这个 session 对象装入 threadlocal 中,其实它是放入一个 Map 中,你可以查看 ThreadLocal 原代码。

              }

 

        return session;

    }

 

       /**

      *  Rebuild hibernate session factory

     *

     */

       public static void rebuildSessionFactory() {

              try {

                     configuration.configure(configFile);

                     sessionFactory = configuration.buildSessionFactory();

              } catch (Exception e) {

                     System.err

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

                     e.printStackTrace();

              }

       }

 

       /**

     *  Close the single hibernate session instance.

     *

     *  @throws HibernateException

     */

    public static void closeSession() throws HibernateException {

        Session session = (Session) threadLocal.get();    // 因为 session 只是方法局部变量,在 threadlocal 中有 session ,所以只能通过 threadlocal.get() 方法来获得

        threadLocal.set(null);

 

        if (session != null) {

            session.close();

        }

    }

 

       /**

     *  return session factory

     *

     */

       public static org.hibernate.SessionFactory getSessionFactory() {

              return sessionFactory;

       }

 

       /**

     *  return session factory

     *

     *    session factory will be rebuilded in the next call

     */

       public static void setConfigFile(String configFile) {

              HibernateSessionFactory.configFile = configFile;

              sessionFactory = null;

       }

 

       /**

     *  return hibernate configuration

     *

     */

       public static Configuration getConfiguration() {

              return configuration;

       }

 

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hibernate 是一种流行的 ORM(对象关系映射)框架,它可以帮助开发者将 Java 对象映射到关系型数据库中。下面是使用 Hibernate 的基本步骤: 1. 引入 Hibernate 的依赖包(jar 文件)和数据库驱动程序。 2. 配置 Hibernate 的配置文件(hibernate.cfg.xml)和映射文件(*.hbm.xml)。 - 配置文件中包括数据库连接信息、Hibernate 的配置参数以及其他信息。 - 映射文件中定义了 Java 对象和数据库表之间的映射关系。 3. 在 Java 代码中创建 SessionFactory 对象,并使用该对象创建 Session 对象。 - SessionFactory 是线程安全的,应该在应用程序启动时创建。 - Session 是轻量级的,应该在每个事务或操作中创建。 4. 使用 Session 对象来执行 CRUD(增删改查)操作。 - 使用 save() 方法来插入新数据,使用 delete() 方法来删除数据,使用 update() 方法来修改数据,使用 get() 或 load() 方法来查询数据。 5. 在程序结束时关闭 Session 对象和 SessionFactory 对象。 下面是一个使用 Hibernate 进行 CRUD 操作的示例代码: ``` // 创建 Configuration 对象,并读取 hibernate.cfg.xml 配置文件 Configuration configuration = new Configuration().configure(); // 创建 SessionFactory 对象 SessionFactory sessionFactory = configuration.buildSessionFactory(); // 创建 Session 对象 Session session = sessionFactory.openSession(); // 插入新数据 Dog dog = new Dog("Tom", 2); session.save(dog); // 查询数据 Dog dog1 = (Dog) session.get(Dog.class, 1); // 修改数据 dog1.setAge(3); session.update(dog1); // 删除数据 session.delete(dog1); // 关闭 Session 对象和 SessionFactory 对象 session.close(); sessionFactory.close(); ``` 这是一个简单的 Hibernate 示例,你可以根据自己的需要添加更多的数据操作和业务逻辑。同时,你也需要熟悉 Hibernate 的各种配置参数和 API,以更好地使用 Hibernate 进行开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值