Hibernate入门指导 - Hibernate官方文档

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.usernameconnection.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对象。



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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 在Tomcat中快速上手 1.1. 开始Hibernate之旅 1.2. 第一个持久化类 1.3. 映射cat 1.4. 与Cat同乐 1.5. 结语 2. 架构(Architecture) 2.1. 概况(Overview) 2.2. 实例状态 2.3. JMX整合 2.4. 对JCA的支持 3. 配置 3.1. 可编程的配置方式 3.2. 获得SessionFactory 3.3. JDBC连接 3.4. 可选的配置属性 3.4.1. SQL方言 3.4.2. 外连接抓取(Outer Join Fetching) 3.4.3. 二进制流 (Binary Streams) 3.4.4. 二级缓存与查询缓存 3.4.5. 查询语言中的替换 3.4.6. Hibernate的统计(statistics)机制 3.5. 日志 3.6. 实现NamingStrategy 3.7. XML配置文件 3.8. J2EE应用程序服务器的集成 3.8.1. 事务策略配置 3.8.2. JNDI绑定的SessionFactory 3.8.3. JTA和Session的自动绑定 3.8.4. JMX部署 4. 持久化类(Persistent Classes) 4.1. 一个简单的POJO例子 4.1.1. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators) 4.1.2. 实现一个默认的(即无参数的)构造方法(constructor) 4.1.3. 提供一个标识属性(identifier property)(可选) 4.1.4. 使用非final的类 (可选) 4.2. 实现继承(Inheritance) 4.3. 实现equals()和hashCode() 4.4. 动态模型(Dynamic models) 5. 对象/关系数据库映射基础(Basic O/R Mapping) 5.1. 映射定义(Mapping declaration) 5.1.1. Doctype 5.1.2. hibernate-mapping 5.1.3. class 5.1.4. id 5.1.4.1. Generator 5.1.4.2. 高/低位算法(Hi/Lo Algorithm) 5.1.4.3. UUID算法(UUID Algorithm ) 5.1.4.4. 标识字段和序列(Identity columns and Sequences) 5.1.4.5. 程序分配的标识符(Assigned Identifiers) 5.1.4.6. 触发器实现的主键生成器(Primary keys assigned by triggers) 5.1.5. composite-id 5.1.6. 鉴别器(discriminator) 5.1.7. 版本(version)(可选) 5.1.8. timestamp (optional) 5.1.9. property 5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 组件(component), 动态组件(dynamic-component) 5.1.13. properties 5.1.14. 子类(subclass) 5.1.15. 连接的子类(joined-subclass) 5.1.16. 联合子类(union-subclass) 5.1.17. 连接(join) 5.1.18. 键(key) 5.1.19. 字段和规则元素(column and formula elements) 5.1.20. 引用(import) 5.1.21. any 5.2. Hibernate 的类型 5.2.1. 实体(Entities)和值(values) 5.2.2. 基本值类型 5.2.3. 自定义值类型 5.3. SQL中引号包围的标识符 5.4. 其他元数据(Metadata) 5.4.1. 使用 XDoclet 标记 5.4.2. 使用 JDK 5.0 的注解(Annotation) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合元素(Collection elements) 6.2.3. 索引集合类(Indexed collections) 6.2.4. 值集合于多对多关联(Collections of values and many-to-many associations) 6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 三重关联(Ternary associations) 6.3.4. 使用<idbag> 6.4. 集合例子(Collection example) 7. 关联关系映射 7.1. 介绍 7.2. 单向关联(Unidirectional associations) 7.2.1. 多对一(many to one) 7.2.2. 一对一(one to one) 7.2.3. 一对多(one to many) 7.3. 使用连接表的单向关联(Unidirectional associations with join tables) 7.3.1. 一对多(one to many) 7.3.2. 多对一(many to one) 7.3.3. 一对一(one to one) 7.3.4. 多对多(many to many) 7.4. 双向关联(Bidirectional associations) 7.4.1. 一对多(one to many) / 多对一(many to one) 7.4.2. 一对一(one to one) 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) 7.5.1. 一对多(one to many) /多对一( many to one) 7.5.2. 一对一(one to one) 7.5.3. 多对多(many to many) 8. 组件(Component)映射 8.1. 依赖对象(Dependent objects) 8.2. 在集合中出现的依赖对象 8.3. 组件作为Map的索引(Components as Map indices ) 8.4. 组件作为联合标识符(Components as composite identifiers) 8.5. 动态组件 (Dynamic components) 9. 继承映射(Inheritance Mappings) 9.1. 三种策略 9.1.1. 每个类分层结构一张表(Table per class hierarchy) 9.1.2. 每个子类一张表(Table per subclass) 9.1.3. 每个子类一张表(Table per subclass),使用辨别标志(Discriminator) 9.1.4. 混合使用“每个类分层结构一张表”和“每个子类一张表” 9.1.5. 每个具体类一张表(Table per concrete class) 9.1.6. Table per concrete class, using implicit polymorphism 9.1.7. 隐式多态和其他继承映射混合使用 9.2. 限制 10. 与对象共事 10.1. Hibernate对象状态(object states) 10.2. 使对象持久化 10.3. 装载对象 10.4. 查询 10.4.1. 执行查询 10.4.1.1. 迭代式获取结果(Iterating results) 10.4.1.2. 返回元组(tuples)的查询 10.4.1.3. 标量(Scalar)结果 10.4.1.4. 绑定参数 10.4.1.5. 分页 10.4.1.6. 可滚动遍历(Scrollable iteration) 10.4.1.7. 外置命名查询(Externalizing named queries) 10.4.2. 过滤集合 10.4.3. 条件查询(Criteria queries) 10.4.4. 使用原生SQL的查询 10.5. 修改持久对象 10.6. 修改脱管(Detached)对象 10.7. 自动状态检测 10.8. 删除持久对象 10.9. 在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scopes) 11.1.1. 操作单元(Unit of work) 11.1.2. 应用程序事务(Application transactions) 11.1.3. 关注对象标识(Considering object identity) 11.1.4. 常见问题 11.2. 数据库事务声明 11.2.1. 非托管环境 11.2.2. 使用JTA 11.2.3. 异常处理 11.3. 乐观并发控制(Optimistic concurrency control) 11.3.1. 应用程序级别的版本检查(Application version checking) 11.3.2. 长生命周期session和自动版本化 11.3.3. 脱管对象(deatched object)和自动版本化 11.3.4. 定制自动版本化行为 11.4. 悲观锁定(Pessimistic Locking) 12. 拦截器与事件(Interceptors and events) 12.1. 拦截器(Interceptors) 12.2. 事件系统(Event system) 12.3. Hibernate的声明式安全机制 13. 批量处理(Batch processing) 13.1. 批量插入(Batch inserts) 13.2. 批量更新(Batch updates) 13.3. 大批量更新/删除(Bulk update/delete) 14. HQL: Hibernate查询语言 14.1. 大小写敏感性问题 14.2. from子句 14.3. 关联(Association)与连接(Join) 14.4. select子句 14.5. 聚集函数 14.6. 多态查询 14.7. where子句 14.8. 表达式 14.9. order by子句 14.10. group by子句 14.11. 子查询 14.12. HQL示例 14.13. 批量的UPDATE & DELETE语句 14.14. 小技巧 & 小窍门 15. 条件查询(Criteria Queries) 15.1. 创建一个Criteria 实例 15.2. 限制结果集内容 15.3. 结果集排序 15.4. 关联 15.5. 动态关联抓取 15.6. 查询示例 15.7. 投影(Projections)、聚合(aggregation)和分组(grouping) 15.8. 离线(detached)查询和子查询 16. Native SQL查询 16.1. 创建一个基于SQL的Query 16.2. 别名和属性引用 16.3. 命名SQL查询 16.3.1. 使用return-property来明确地指定字段/别名 16.3.2. 使用存储过程来查询 16.3.2.1. 使用存储过程的规则和限制 16.4. 定制SQL用来create,update和delete 16.5. 定制装载SQL 17. 过滤数据 17.1. Hibernate 过滤器(filters) 18. XML映射 18.1. 用XML数据进行工作 18.1.1. 指定同时映射XML和类 18.1.2. 只定义XML映射 18.2. XML映射元数据 18.3. 操作XML数据 19. 提升性能 19.1. 抓取策略(Fetching strategies) 19.1.1. 调整抓取策略(Tuning fetch strategies) 19.1.2. 单端关联代理(Single-ended association proxies) 19.1.3. 实例化集合和代理(Initializing collections and proxies) 19.1.4. 使用批量抓取(Using batch fetching) 19.1.5. 使用子查询抓取(Using subselect fetching) 19.1.6. 使用延迟属性抓取(Using lazy property fetching) 19.2. 二级缓存(The Second Level Cache) 19.2.1. 缓存映射(Cache mappings) 19.2.2. 策略:只读缓存(Strategy: read only) 19.2.3. 策略:读/写缓存(Strategy: read/write) 19.2.4. 策略:非严格读/写缓存(Strategy: nonstrict read/write) 19.2.5. 策略:事务缓存(transactional) 19.3. 管理缓存(Managing the caches) 19.4. 查询缓存(The Query Cache) 19.5. 理解集合性能(Understanding Collection performance) 19.5.1. 分类(Taxonomy) 19.5.2. Lists, maps 和sets用于更新效率最高 19.5.3. Bag和list是反向集合类中效率最高的 19.5.4. 一次性删除(One shot delete) 19.6. 监测性能(Monitoring performance) 19.6.1. 监测SessionFactory 19.6.2. 数据记录(Metrics) 20. 工具箱指南 20.1. Schema自动生成(Automatic schema generation) 20.1.1. 对schema定制化(Customizing the schema) 20.1.2. 运行该工具 20.1.3. 属性(Properties) 20.1.4. 使用Ant(Using Ant) 20.1.5. 对schema的增量更新(Incremental schema updates) 20.1.6. 用Ant来增量更新schema(Using Ant for incremental schema updates) 21. 示例:父子关系(Parent Child Relationships) 21.1. 关于collections 21.2. 双向的一对多关系(Bidirectional one-to-many) 21.3. 级联生命周期(Cascading lifecycle) 21.4. 级联与未保存值(Cascades and unsaved-value) 21.5. 结论 22. 示例:Weblog 应用程序 22.1. 持久化类 22.2. Hibernate 映射 22.3. Hibernate 代码 23. 示例:复杂映射实例 23.1. Employer(雇主)/Employee(雇员) 23.2. Author(作家)/Work(作品) 23.3. Customer(客户)/Order(订单)/Product(产品) 23.4. 杂例 23.4.1. "Typed" one-to-one association 23.4.2. Composite key example 23.4.3. Content based discrimination 23.4.4. Associations on alternate keys 24. 最佳实践(Best Practices)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值