首先要感谢我所在的 team 意识到了传统 jdbc 开发的种种不足,转而开始关注 o/r mapping 领域的成果。说到 o/r mapping,我认为在对象数据库还没有真正成熟的时候它是一个不错的选择,看看 sun 的 jdo 2.0 规范吧,它的即将发布将会把这个领域推向更高的境界。再看看我们的开源社区呢,喔!发现了 hibernate!从现在开始,我的焦点将放在 hibernate 上面,一个优秀的o/r mapping 工具。
在没有正式开始旅行之前,让我们区分几个名词。pojo:在 hibernate 中代表包含 seter、geter 这些最基本操作的值对象。而 bo:代表包含一些业务逻辑的值对象,它的作用域很大,也就是说 bo 在充当持久类的同时可以传到 ui 层。po:代表持久对象,是纳入 hibernate 管理框架中的,在一定程度上可以和值对象的概念互换,值对象经过 hibernate 进行处理,就变成了 po 。hibernate 配置文件:hibernate.cfg.xml 或 hibernate.properties,不过推荐使用 xml 格式。映射文件 *.hbm.xml:映射文件的作用是将 pojo 与关系型数据库数据相绑定,作为一个桥梁。另外,为数据库中的表进行手工编写映射文件可不是件好差事,幸好开源社区中也有一群同样想法的人,他们开发了 hibernatesynchronizer 映射工具,可到 http://www.binamics.com/hibernatesync/eclipse2.1/ 下载。
好了,现在去 http://www.hibernate.org 下载 hibernate 的开发包(目前的版本是 2.1.6)。接着打开 eclipse 2.1,在更新管理器中安装 hibernatesynchronizer。据说 eclipse 3.0 已内置映射工具,不过我没有试。安装完毕后,新建一个 web 应用程序 hibernatetest,接着为这个应用程序添加 hibernate 类库 hibernate-2.1.6/hibernate-2.1/hibernate2.jar 及其依赖类库、数据库连接包,强烈建议把 hibernate-2.1.6/hibernate-2.1/lib 下的所有类库全部加载,如下图:

接着使用 hibernatesynchronizer 来生成 hibernate.cfg.xml 文件,新建——>其他——>hibernate configuration file,我使用的是 sql server 数据库,各项配置参数见下图:

生成出来的 hibernate.cfg.xml 文件:

在项目的 src 目录下新建四个包,分别是bo、bo.base、bo.mapping、com.dao,具体什么作用,到时候他们都会一一呈献。在开始映射文件前还要做一件事,为应用程序 hibernatetest 配置 hibernatesynchronizer ,我更喜欢自己写 dao ,所以没有配置 data access objects,其他各项参数如下图:

被映射的表 autoinfo 结构如下,id为其主键:

新建——>其他——>hibernate mapping file,配置好参数再“refresh”后,选择要映射的表,注意千万不要在 800*600 下映射文件!否则有些按钮不会出现,各项配置参数见下图:

终于、终于,映射文件 autoinfo.hbm.xml 终于出来了!
<?xml version="1.0"?> <hibernate-mapping package="bo.base">
<!doctype hibernate-mapping public
"-//hibernate/hibernate mapping dtd//en"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<class name="autoinfo" table="autoinfo">
<property
column="owner_dept"
length="500"
name="ownerdept"
not-null="false"
type="string"
/>
<property
column="license_plate"
length="50"
name="licenseplate"
not-null="false"
type="string"
/>
<property
column="owner"
length="50"
name="owner"
not-null="false"
type="string"
/>
<property
column="owner_adderss"
length="1000"
name="owneradderss"
not-null="false"
type="string"
/>
<property
column="id"
length="18"
name="id"
not-null="true"
type="integer"
/>
</class>
</hibernate-mapping>
需要修改一下 autoinfo.hbm.xml 文件为其定义主键,把:
<property
column="id"
length="18"
name="id"
not-null="true"
type="integer"
/>
替换为:
<id name="id" column="id" type="integer">
<generator class="native"/>
</id>
再接再厉,为映射文件生成 pojo。修改 hibernate.cfg.xml 文件在 </session-factory> 标签的上面加上刚才映射的文件 <mapping resource="bo/mapping/autoinfo.hbm.xml" />。接着在“包资源管理器”中点击 autoinfo.hbm.xml 右键,hibernate synchronizer——>synchronize files。再看看 src 中的包:

o/r mapping 的旅程先到这里吧,后面的路将会越来越坎坷!你准备好了吗?
(请注意!引用、转贴本文应注明原作者:rosen jiang 以及出处:http://blog.csdn.net/rosen)
闽公网安备 35060202000074号