码迷,mamicode.com
首页 > Web开发 > 详细

hibernate 创建工厂类

时间:2016-05-01 21:43:01      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

package cn.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 创建一个工厂类 用于创建SessionFactory唯一的一个
 */
public class SessionFactoryUtils {
    private static SessionFactory sessionFactory;
    // 在静态的代码块中创建这个对象
    static {
        // 1:创建Configuration对象,用于读取hibernate.cfg.xml文件
        Configuration config = new Configuration();
        // 默认读取hibernte.cfg.xml
        config.configure();
        // 2:创建SessionFactory对象
        sessionFactory = config.buildSessionFactory();
    }
    //3:提供一个静态的方法-返回SessionFactory的实例
    public static SessionFactory getSessionFatory(){
        return sessionFactory;
    }
}

步4:测试是否连接数据库成功 – 获取 Connection对象
    @Test
    public void test1() {
        // 1:获取 SessionFactory
        SessionFactory sf = SessionFactoryUtils.getSessionFatory();
        // 打开一个新的连接会话
        Session session = sf.openSession();//
        // 通过doWork获取一个COnnection,则所有在execute里面执行的方法都被Session控制
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                System.err.println("连接是:" + connection);
            }
        });
        session.close();
    }

 

package cn.hibernate;

 

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

/**

 * 创建一个工厂类用于创建SessionFactory唯一的一个

 */

publicclass SessionFactoryUtils {

    privatestatic SessionFactory sessionFactory;

    // 在静态的代码块中创建这个对象

    static {

         // 1:创建Configuration对象,用于读取hibernate.cfg.xml文件

         Configuration config = new Configuration();

         // 默认读取hibernte.cfg.xml

         config.configure();

         // 2:创建SessionFactory对象

         sessionFactory = config.buildSessionFactory();

    }

    //3:提供一个静态的方法-返回SessionFactory的实例

    publicstatic SessionFactory getSessionFatory(){

         returnsessionFactory;

    }

}

 

4:测试是否连接数据库成功 获取 Connection对象

    @Test

    publicvoid test1() {

         // 1:获取 SessionFactory

         SessionFactory sf = SessionFactoryUtils.getSessionFatory();

         // 打开一个新的连接会话

         Session session = sf.openSession();//

         // 通过doWork获取一个COnnection,则所有在execute里面执行的方法都被Session控制

         session.doWork(new Work() {

             @Override

             publicvoid execute(Connection connection) throws SQLException {

                  System.err.println("连接是:" + connection);

             }

         });

         session.close();

    }

 

hibernate 创建工厂类

标签:

原文地址:http://www.cnblogs.com/fujilong/p/5451098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!