Hibernate自我总结(Configuration接口)

来源:互联网 发布:java ee 6权威指南 编辑:程序博客网 时间:2024/06/17 05:22

刚毕业,虽说工作上使用Hibernate完全没问题,但有时候总觉得自己学的不够深入,就看了看《精通 Hibernate:Java 对象持久化技术详解(第2版)》,并且写下总结,好让自己加深理解得以掌握。


Hibernate主要核心接口:Cofiguration接口、SessionFactory接口、Session接口、Transaction接口、Query和Criteria接口。


首先Configuration接口,该接口主要用来记载Hibernate配置信息(包括数据库url、用户名、密码等信息),以及作为启动Hibernate的入口和创建SessionFactory等。


首先(导入Hibernate所需要包以及相应数据库驱动包)建立一个hibernate.cfg.xml文件,用于动态配置Hibernate配置信息(比较符合实际生产 需要,思路清晰)。

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory>    <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>        <property name="connection.username">admin</property>    <property name="connection.password">111111</property>    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    <!-- 最大连接数 -->      <property name="hibernate.c3p0.max_size">300</property>    <!-- 最小连接数 -->      <property name="hibernate.c3p0.min_size">5</property>    <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 ***-->    <property name="hibernate.c3p0.timeout">120000</property>    <!-- 最大的PreparedStatement的数量 -->    <property name="hibernate.c3p0.max_statements">0</property>    <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->    <property name="hibernate.c3p0.idle_test_period">120</property>    <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->    <property name="hibernate.c3p0.acquire_increment">2</property>    <!-- 每次都验证连接是否可用 -->    <property name="hibernate.c3p0.validate">true</property>    <property name="show_sql">true</property>    <!-- 下方配置pojo类相应的配置文件 -->    <mapping resource="com/test/dx/pojo/TCjry.hbm.xml" />    <mapping resource="com/test/dx/pojo/TJsxxjl.hbm.xml" />    <mapping resource="com/test/dx/pojo/TXcgl.hbm.xml" />    <mapping resource="com/test/dx/pojo/TPbxmb.hbm.xml" />    <mapping resource="com/test/dx/pojo/TZtk.hbm.xml" />    </session-factory></hibernate-configuration>

接着(单例模式)创建HibernateSessionFactory类,静态描述Configuration对象以及SessionFactory对象。

package com.test.base;import java.util.Date;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 {        Session session = (Session) threadLocal.get();        if (session == null || !session.isOpen()) {            if (sessionFactory == null) {                rebuildSessionFactory();            }            session = (sessionFactory != null) ? sessionFactory.openSession() : null;            session.clear();            threadLocal.set(session);        }        return session;    }    /**     *  Rebuild hibernate session factory     *     */    public static void rebuildSessionFactory() {        try {            configuration = new Configuration();            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();        threadLocal.set(null);        if (session != null) {            session.close();        }    }    /**     * Add by lyj     */    public static void finalCloseSession() {        Session s = threadLocal.get();        if (null != s) {            if (s.isOpen()) {                //org.apache.log4j.Logger.getLogger("系统提示:").warn("程序出现没有关闭的Session!由系统自动关闭!"+(new Date()));                s.close();            } else {                //org.apache.log4j.Logger.getLogger("系统提示:").warn("线程不为空!由系统自动清空!"+(new Date()));            }            threadLocal.set(null);        }    }    /**     *  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;    }}

配置好HibernateSessionFactory类后,就可以愉快地用Hibernate玩耍啦!


//获取SessionSession s = HibernateSessionFactory.getSession();//根据主键利用session加载某类对象TCjry tc = (TCjry)session.load(TCjry.class, kcId);
原创粉丝点击