您的位置:首页 > 其它

Hibernate入门指导 - Hibernate官方文档

2016-10-10 17:18 357 查看

2.使用Hibernate API和hbm.xml映射文件教程

[说明] This tutorial is located within the download bundle under basic/.

目标:

√ 驱动(引导)一个Hibernate SessionFactory

√ 使用Hibernate 映射(hbm.xml)文件来提供映射信息

√使用Hibernate API

2.1 Hibernate配置文件

在本教程中,hibernate.cfg.xml文件定义了Hibernate的配置信息。

connection.driver_class, connection.url, connection.username和connection.password这些<property/>元素定义了JDBC连接的信息。本教程使用的是H2这款内存数据库(in-memory database),所以这些属性值全部是为了运行在H2的内存模式而指定的。connection.pool_size被用于配置Hibernate内置连接池的数量。

[注意] 内置的Hibernate连接池决不能用于生产阶段。相对于能用于生产的(production-ready)连接池,它缺乏一些特征。

dialect属性指定了和Hibernate交互的特定数据库类型。

[提示]在大多数情况下,Hibernate能够恰当地决定使用那种方言。如果你的应用程序是针对各种数据库的,那么此时这个属性就很有用。

The hbm2ddl.auto property enables automatic generation of database schemas directly into the database.

最后,还需要添加持久化类的映射文件到配置中。利用<mapping/>元素的resource属性,Hibernate便会在借助java.lang.ClassLoader检查时,把这些映射放置到类路径(classpath)资源中。

驱动一个Hibernate的SessionFactory有很多种方式和选择。更多细节,请查看“Native Bootstrapping topical guide”。

2.2 实体Java类

 本教程使用到的实体类是org.hibernate.tutorial.hbm.Event

关于实体类:

该类为属性的getter和setter方法采用了标准的JavaBean命名规范,并且也为域使用了私用可见性。尽管这是推荐的设计方式,但并不是必须的。
所有持久化类必须要求有不带参的构造方法(也是JavaBean的规范)。Hibernate需要使用Java反射为你创建对象。构造方法可以是私有的。但是,package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.

2.3  映射文件

本教程的映射文件是类路径资源org/hibernate/tutorial/hbm/Event.hbm.xml(上面提到过)。
Hibernate使用映射元数据来决定怎样加载和储存持久类对象。Hibernate映射文件是提供给Hibernate映射元数据的一种方式(译者注:还有另一种方式是使用properties文件)。
例子1 class映射元素
<class name="Event" table="EVENTS">
...
</class>


class映射文件的属性:

name属性 (combined here with the package attribute from the containing <hibernate-mapping/> element) 指定定义实体类的全限定名(FQN)。
table属性指定包含该实体类数据的数据库表。

这样一来,Event类的实例便对应了EVENTS数据库表的行。
例子2 id映射元素
....
....

2.4 示例代码

org.hibernate.tutorial.hbm.NativeApiIllustrationTest类说明了如何使用Hibernate API。

[说明] 为方便起见,本教程的示例是使用JUnit测试用例来写的。这种方式的好处之一就是,setUp和tearDown可以大致地展示了org.hibernate.SessionFactory是如何在应用程序启动时被创建的以及如何在应用程序生命周期的结束时被销毁的。
例子4 获取org.hibernate.SessionFactory
protected void setUp() throws Exception {
// SessionFacotry在一个程序中只被创建一次
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // 从hibernate.cfg.xml中配置设置信息
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}


The setUp method first builds a org.hibernate.boot.registry.StandardServiceRegistry instance which incorporates configuration information into a working set of Services for use by the SessionFactory. 在本教程中,我们把所有的配置信息都定义在hibernate.cfg.xml中,so there is not much
interesting to see here.

org.hibernate.boot.Metadata represents the complete, partially validated view of the application domain model which the SessionFactory will be based on.

驱动过程的最后一步是创建SessionFactory。SessionFactory是一个被实例化一次来用于整个应用程序的线程安全的对象。
SessionFactory承担org.hibernate.Session实例的工厂类,which should be thought of as a corollary to a "unit of work".

例子5 保存实体
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Event( "Our very first event!", new Date() ) );
session.save( new Event( "A follow up event", new Date() ) );
session.getTransaction().commit();
session.close();

testBasicUsage()方法首先创建一些Event对象,然后通过调用save()方法将它们交由Hibernate管理。此时Hibernate的责任是将每个Event插入到数据库中。

例子6 获取实体类列表
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( "from Event" ).list();
for ( Event event : (List<Event>) result ) {
System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
}
session.getTransaction().commit();
session.close();
在这个例子中,Hibernate查询语言(Hibernate Query Language,HQL)通过生成合适的SELECT SQL语句传递给数据库,并将结果集数据填充到Event对象中,以此来从数据库中加载所有存在的Event对象。

-------------------------------------------------------------------------
转载请注明出处!

本文翻译自Hibernate Getting Started Guide - jboss.org 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate