这一章,作者从Hibernate的架构,Hibernate的配置,Hibernate会话等整体的介绍了下Hibernate.
作为一个Hibernate devloper,你关心的并不是object被存储的过程,而是如何去存储object。如果一个class以单独的形式存在,不是一个合成类里面的成员,那么他就必须定义一个ID。Hibernate提供很多ID生成器,从数据库提供的生成器到利用系统的时钟或者网络地址来生成一个ID。object还必须遵守javabean规范。所有要被持久的类都要定义个默认的构造函数,为了Hibernate能从数据库取出object的时候来实例化它。
Hibernate还支持复杂的类,继承结构能很轻松的被持久,并且其多态性依然能被保持。Hibernate还可以持久作为类的属性的Collections.当Collections所属的类被持久的时候,Collections将自动被持久,或者应用程序可以控制单独的持久Collections。
Hibernate的一个主要用途就是连接数据库,Hibernate可以支持很多种数据库,它支持基本的SQL而且支持不同数据库的方言SQL(这个功能是通过dialect class实现的)。但是Hibernate并不是唯一的处于应用程序与数据库之间的技术。Hibernate可以应用于依赖服务器处理servlet和EJB的应用程序。在这些情况下,用JNDI来处理数据库资源是很正常的。这是Hibernate就可以通过修改一下配置信息来得到这些资源。
下面就来说下Hibernate配置:
下面是一个通过hibernate.cfg.xml文件来配置Hibernate:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver">com.mysql.jdbc.Driver</property>
<property name="connection.url"
jdbc:mysql://localhost/products</property>
<property name="dialect">
net.sf.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
通过这个xml文件你可以配置Hibernate连接数据库的信息,你也可以通过配置这个文件来得到JNDI和JDBC的连接。
下面的配置信息则是描述一个class和数据库表之间的联系的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="Notes"
table="notes">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="info" type="string"/>
<property name="count" type="integer" not-null="true"/>
<property name="zipcode" type="string"/>
<property name="fullname" type="string"/>
</class>
</hibernate-mapping>
Hibernate Sessions
当你在应用程序里面用hibernate的时候,一个单线程的SessionFactory就会建立,这个SessionFactory通过上面的配置文件为你的程序配置Hibernate,然后生成Sessions.SessionFactory是一贯重量级的,所以在每个程序里面就建立一个SessionFactory。一个Session就是一次与数据库之间的会话。当一个Session被实例化的时候就建立一个数据库连接,这个交互应该很快,以防止数据库连接的打开是无休止的。与数据库之间的交互要养成用transction的习惯。
Hibernate callbacks
public Boolean onSave(Session s); - called before the object is saved to the database
public Boolean onUpdate(Session s); - called before the object is updated
public boolean onDelete(Session s); - called before the object is deleted
public Boolean onLoad(Session s); - called after the object is loaded from the database