整个类层次结构可以被映射到单张表。这张表把所有类的所有属性的列都包括在层次结构中。由特定行表示的具体子类通过一个类型辨别标志列的值进行识别。这个映射策略在性能和简单性方面都胜出一筹。它是表示多态的最佳方法---多态和非多态的查询都执行得很好---并且更易于手工实现。不用复杂的联结或者联合也有可能生成特殊的报表。有一个重大的问题:子类声明的属性的列必须声明为可为空。
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>hibernateTest</groupId> <artifactId>hibernateTest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>hibernateTest</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.3.1.GA</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.4.GA</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.3.0</version> <scope>runtime</scope> </dependency> </dependencies> <build> <finalName>hibernateTest</finalName> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="sessionFactory"> <!-- 指定连接数据库所用的驱动 --> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <!-- 指定连接数据库的url,hibernate连接的数据库名 --> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="hibernate.connection.useUnicode">true</property> <property name="hibernate.connection.characterEncoding">gbk</property> <!-- 指定连接数据库的用户名 --> <property name="hibernate.connection.username">system</property> <!-- 指定连接数据库的密码 --> <property name="hibernate.connection.password">password</property> <!-- 指定连接池里最大连接数 --> <property name="hibernate.c3p0.max_size">20</property> <!-- 指定连接池里最小连接数 --> <property name="hibernate.c3p0.min_size">5</property> <!-- 指定连接池里连接的超时时长,以秒为单位 --> <property name="hibernate.c3p0.timeout">120</property> <!-- 指定连接池里最大缓存多少个Statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <!-- 每隔XX秒检查连接池里的空闲连接 ,单位是秒 --> <property name="hibernate.c3p0.idle_test_period">120</property> <!-- 当连接池里面的连接用完的时候,C3P0一次获取的新的连接数 --> <property name="hibernate.c3p0.acquire_increment">2</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <!-- 显示Hibernate持久化操作所生成的SQL --> <property name="show_sql">true</property> <!-- 将SQL脚本进行格式化后再输出 --> <property name="hibernate.format_sql">true</property> <!-- 罗列所有的映射文件 --> <mapping resource="pojo/BillingDetails.hbm.xml" /> </session-factory> </hibernate-configuration>
父类, pojo/BillingDetails .java:
package pojo; public class BillingDetails { private String id; private String owner; public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
子类,pojo/BankAccount.java:
package pojo; public class BankAccount extends BillingDetails { private String account; private String bankName; private String swift; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getSwift() { return swift; } public void setSwift(String swift) { this.swift = swift; } }
子类,pojo/CreditCard.java:
package pojo; public class CreditCard extends BillingDetails{ private String number; private String expMonth; private String expYear; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getExpMonth() { return expMonth; } public void setExpMonth(String expMonth) { this.expMonth = expMonth; } public String getExpYear() { return expYear; } public void setExpYear(String expYear) { this.expYear = expYear; } }
映射文件,pojo/BillingDetails.hbm.xml , 重点都在这个映射文件上,请注意些。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="pojo"> <class name="BillingDetails" table="BILLING_DETAILS" dynamic-insert="true" dynamic-update="true"> <id name="id" column="BILLING_DETAILS_ID" type="string"> <generator class="uuid.hex" /> </id> <!-- 按顺序discriminator元素好像只能在id后面 --> <discriminator column="BILLING_DETAILS_TYPE" type="string"/> <property name="owner" column="OWNER" type="string" /> <subclass name="BankAccount" discriminator-value="BA"> <property name="account" column="BA_ACCOUNT" type="string" /> <property name="bankName" column="BA_BANKNAME" type="string" /> <property name="swift" column="BA_SWIFT" type="string"/> </subclass> <subclass name="CreditCard" discriminator-value="CC"> <property name="number" column="CC_NUMBER" type="string" /> <property name="expMonth" column="CC_EXP_MONTH" type="string" /> <property name="expYear" column="CC_EXP_YEAR" type="string"/> </subclass> </class> </hibernate-mapping>
util/HibernateUtil.java:
package util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static{ try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable e) { throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void shutdown(){ getSessionFactory().close(); } }
util/Manager.java:
package util; import org.hibernate.Session; import org.hibernate.Transaction; import pojo.BankAccount; import pojo.CreditCard; public class Manager { public static void main(String[] args) { BankAccount ba = new BankAccount(); ba.setAccount("个人帐户"); ba.setBankName("付海东"); ba.setOwner("fuhaidong"); ba.setSwift("aaa"); CreditCard cc = new CreditCard(); cc.setOwner("fuhaidong"); cc.setNumber("100000000"); cc.setExpYear("2010"); cc.setExpMonth("10"); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); //插入 session.save(cc); session.save(ba); session.createQuery("from CreditCard").list(); session.createQuery("from BankAccount").list(); transaction.commit(); session.close(); } }
输出的sql:
Hibernate: insert into BILLING_DETAILS (OWNER, CC_NUMBER, CC_EXP_MONTH, CC_EXP_YEAR, BILLING_DETAILS_TYPE, BILLING_DETAILS_ID) values (?, ?, ?, ?, 'CC', ?) Hibernate: insert into BILLING_DETAILS (OWNER, BA_ACCOUNT, BA_BANKNAME, BA_SWIFT, BILLING_DETAILS_TYPE, BILLING_DETAILS_ID) values (?, ?, ?, ?, 'BA', ?) Hibernate: select creditcard0_.BILLING_DETAILS_ID as BILLING1_0_, creditcard0_.OWNER as OWNER0_, creditcard0_.CC_NUMBER as CC7_0_, creditcard0_.CC_EXP_MONTH as CC8_0_, creditcard0_.CC_EXP_YEAR as CC9_0_ from BILLING_DETAILS creditcard0_ where creditcard0_.BILLING_DETAILS_TYPE='CC' Hibernate: select bankaccoun0_.BILLING_DETAILS_ID as BILLING1_0_, bankaccoun0_.OWNER as OWNER0_, bankaccoun0_.BA_ACCOUNT as BA4_0_, bankaccoun0_.BA_BANKNAME as BA5_0_, bankaccoun0_.BA_SWIFT as BA6_0_ from BILLING_DETAILS bankaccoun0_ where bankaccoun0_.BILLING_DETAILS_TYPE='BA'
大家可以注意下打印出来的查询的sql语句。
上例中,继承层次结构的根类BillingDetails被映射到表:BILLING_DETAILS.
必须添加一个特殊的列以便在持久化类之间进行区分:辨别标志(discriminator)。这不是持久化类的属性,由hibernate内部使用。列名为BILLING_DETAILS_TYPE,值为字符串---在这个例子中,为"CC"或者"BA"。hibernate自动设置和获取辨别标志的值。
关于超类的属性,用简单的<property>元素映射.
每个子类都有自己的<subclass>元素。子类的属性被映射到BILLING_DETAILS表中的列。记住不允许NOT NULL约束,因为BankAccount实例不会有expMonth属性,且该行的CC_EXP_MONTH字段必须为NULL.
<subclass>元素可以依次包含其它被嵌套的<subclass>元素,直到整个层次结构被映射到表中。
请注意,这里只有一个表:BILLING_DETAILS ,包含了所有属性或字段。
BILLING_DETAILS表:
BILLING_DETAILS_ID
BILLING_DETAILS_TYPE
OWNER
CC_NUMBER
CC_EXP_MONTH
CC_EXP_YEAR
BA_ACCOUNT
BA_BANKNAME
BA_SWIFT