三、使用T/CCU(Table Per Concrete Class with Union)策略来映射
1. 只对Concrete Class建立Table,SuperClass中的property,直接mapping到Concrete Class相应Table的column
2. 对于Concrete Class的mapping,使用union-subclass的方式来Mapping。
Mapping File如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="org.example.hibernate.domain.BillingDetail" abstract="true"> <!-- 必须声明abstract="true"--> <id name="id" column="IDNUM" type="long"> <generator class="hilo"/> </id> <property name="owner" type="string" column="OWNER" length="30" /> <union-subclass name="org.example.hibernate.domain.CreditCard" table="CREDIT_CARD"> <property name="number" type="string" column="NUMBER_CODE" length="20" /> <property name="expMonth" type="string" column="EXP_MONTH" length="2" /> <property name="expYear" type="string" column="EXP_YEAR" length="4" /> </union-subclass> <union-subclass name="org.example.hibernate.domain.BankAccount" table="BANK_ACCOUNT"> <property name="account" type="string" column="ACCOUNT" length="20" /> <property name="bankName" type="string" column="BANK_NAME" length="255" /> <property name="swift" type="string" column="SWIFT" length="3" /> </union-subclass> </class> </hibernate-mapping>
1.当对Concrete Class做save的时候,会首先generate id,以确保该id为2张table的唯一。
CreditCard cc21 = new CreditCard(); cc21.setOwner("jessecia"); cc21.setNumber("123123123123123"); session.save(cc21);
相应的SQL
select max(ids_.IDNUM) from ( select IDNUM from CREDIT_CARD union select IDNUM from BANK_ACCOUNT ) ids_ insert into CREDIT_CARD (OWNER, NUMBER_CODE, EXP_MONTH, EXP_YEAR, IDNUM) values (?, ?, ?, ?, ?)
2.对于BillDetail的Query转为union方式获得。
List list = session.createQuery("from BillingDetail2 bd1 where bd1.owner = :owner") .setParameter("owner", "jessecia") .list();
相应SQL如下:
select billingdet0_.IDNUM as IDNUM0_ , billingdet0_.OWNER as OWNER0_ , billingdet0_.NUMBER_CODE as NUMBER1_1_ , billingdet0_.EXP_MONTH as EXP2_1_ , billingdet0_.EXP_YEAR as EXP3_1_ , billingdet0_.ACCOUNT as ACCOUNT2_ , billingdet0_.BANK_NAME as BANK2_2_ , billingdet0_.SWIFT as SWIFT2_ , billingdet0_.clazz_ as clazz_ from ( select IDNUM , null as SWIFT , EXP_YEAR , null as ACCOUNT , OWNER , EXP_MONTH , NUMBER_CODE , null as BANK_NAME , 1 as clazz_ from CREDIT_CARD union select IDNUM , SWIFT , null as EXP_YEAR , ACCOUNT , OWNER , null as EXP_MONTH , null as NUMBER_CODE , BANK_NAME , 2 as clazz_ from BANK_ACCOUNT ) billingdet0_ where billingdet0_.OWNER=?
上一篇:Class Hierachy的映射策略之T/CCIP