六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 240|回复: 0

重新认识hibernate

[复制链接]

升级  38%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
19
 楼主| 发表于 2013-1-14 23:42:46 | 显示全部楼层 |阅读模式
hibernate.cfg.xml
<?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>        <!-- Database connection settings -->        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>        <property name="connection.username">sa</property>        <property name="connection.password"></property>        <!-- JDBC connection pool (use the built-in) -->        <property name="connection.pool_size">1</property>        <!-- SQL dialect -->        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>        <!-- Enable Hibernate's automatic session context management -->        <property name="current_session_context_class">thread</property>        <!-- Disable the second-level cache  -->        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        <!-- Echo all executed SQL to stdout -->        <property name="show_sql">true</property>        <!-- Drop and re-create the database schema on startup -->        <property name="hbm2ddl.auto">update</property>        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>    </session-factory></hibernate-configuration>
在这里,我们配置了 Hibernate 的SessionFactory — 一个关联于特定数据库全局的工厂(factory)。如果你要使用多个数据库,就要用多个的 <session-factory>,通常把它们放在多个配置文件中(为了更容易启动)。

启动 Hibernate,此过程包括创建一个全局的 SessoinFactory,并把它储存在应用程序代码容易访问的地方。SessionFactory 可以创建并打开新的 Session。一个 Session 代表一个单线程的单元操作,org.hibernate.SessionFactory 则是个线程安全的全局对象,只需要被实例化一次。
我们将创建一个 HibernateUtil 辅助类(helper class)来负责启动 Hibernate 和更方便地操作 org.hibernate.SessionFactory。让我们来看一下它的实现:
package org.hibernate.tutorial.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {    private static final SessionFactory sessionFactory = buildSessionFactory();    private static SessionFactory buildSessionFactory() {        try {            // Create the SessionFactory from hibernate.cfg.xml            return new Configuration().configure().buildSessionFactory();        }        catch (Throwable ex) {            // Make sure you log the exception, as it might be swallowed            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }    }    public static SessionFactory getSessionFactory() {        return sessionFactory;    }}如果你在配置文件中给 org.hibernate.SessionFactory 一个名字,在 它创建后,Hibernate 会试着把它绑定到 JNDI。要完全避免这样的代码,你也可以使用 JMX 部署,让具有 JMX 能力的容器来实例化 HibernateService 并把它绑定到 JNDI。这些高级可选项在后面的章节中会讨论到。

加载并存储对象
package org.hibernate.tutorial;import org.hibernate.Session;import java.util.*;import org.hibernate.tutorial.domain.Event;import org.hibernate.tutorial.util.HibernateUtil;public class EventManager {    public static void main(String[] args) {        EventManager mgr = new EventManager();        if (args[0].equals("store")) {            mgr.createAndStoreEvent("My Event", new Date());        }        HibernateUtil.getSessionFactory().close();    }    private void createAndStoreEvent(String title, Date theDate) {        Session session = HibernateUtil.getSessionFactory().getCurrentSession();        session.beginTransaction();        Event theEvent = new Event();        theEvent.setTitle(title);        theEvent.setDate(theDate);        session.save(theEvent);        session.getTransaction().commit();    }}
sessionFactory.getCurrentSession() 是干什么的呢?首先,只要你持有 org.hibernate.SessionFactory,大可在任何时候、任何地点调用这个方法。getCurrentSession() 方法总会返回“当前的”工作单元。记得我们在hibernate.cfg.xml 中把<property name="current_session_context_class">thread</property>配置选项调整为 "thread" 了吗?因此,因此,当前工作单元被绑定到当前执行我们应用程序的 Java 线程。但是,这并非是完全准确的,你还得考虑工作单元的生命周期范围(scope),它何时开始,又何时结束。
org.hibernate.Session 在第一次被使用的时候,即第一次调用 getCurrentSession() 的时候,其生命周期就开始。然后它被 Hibernate 绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate 会自动把 org.hibernate.Session 从当前线程剥离,并且关闭它。假若你再次调用 getCurrentSession(),你会得到一个新的 org.hibernate.Session,并且开始一个新的工作单元。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表