Welcome 微信登录

首页 / 软件开发 / JAVA / 精通Hibernate之映射继承关系五

精通Hibernate之映射继承关系五2011-08-09本节的范例程序位于配套光盘的sourcecodechapter1414.2目录下,运行该程序前,需要在SAMPLEDB数据库中手工创建COMPANIES表和EMPLOYEES表,然后加入测试数据,相关的SQL脚本文件为/14.2schemasampledb.sql。

在DOS命令行下进入chapter14根目录,然后输入命令:

ant -file build2.xml run

就会运行BusinessService类。BusinessService的main()方法调用test()方法,test()方法依次调用以下方法:

findAllHourlyEmployees():检索数据库中所有的HourlyEmployee对象。

findAllEmployees():检索数据库中所有的Employee对象。

loadCompany():加载一个Company对象。

saveEmployee():保存一个Employee对象。

(1)运行findAllHourlyEmployees()方法,它的代码如下:

tx = session.beginTransaction();

List results=session.find("from HourlyEmployee");

tx.commit();

return results;

在运行Session的find()方法时,Hibernate执行以下select语句:

select * from EMPLOYEES where EMPLOYEE_TYPE="HE" ;

select * from COMPANIES where ID=1;

在加载HourlyEmployee对象时,还会同时加载与它关联的Company对象。

(2)运行findAllEmployees()方法,它的代码如下:

tx = session.beginTransaction();
List results=session.find("from Employee");
tx.commit();
return results;