Hibernate自動(dòng)生成工具-Schema
本文我們主要介紹Hibernate Schema自動(dòng)生成(Automatic schema generation)技術(shù),希望對(duì)大家的學(xué)習(xí)帶來(lái)幫助。
Hibernate Schema自動(dòng)生成可以從你的映射文件使用一個(gè)Hibernate工具生成DDL。 生成的schema包含有對(duì)實(shí)體和集合類表的完整性引用約束(主鍵和外鍵)。涉及到的標(biāo)示符生成器所需的表和sequence也會(huì)同時(shí)生成。
在使用這個(gè)工具的時(shí)候,你必須 通過(guò)hibernate.dialet屬性指定一個(gè)SQL方言(Dialet),因?yàn)镈DL是與供應(yīng)商高度相關(guān)的。
首先,要定制你的映射文件,來(lái)改善生成的Hibernate schema。對(duì)Hibernate schema定制化(Customizing the schema)
很多Hibernate映射元素定義了可選的length、precision 或者 scale屬性。你可以通過(guò)這個(gè)屬性設(shè)置字段的長(zhǎng)度、精度、小數(shù)點(diǎn)位數(shù)。
- <property name="zip" length="5"/>
- <property name="balance" precision="12" scale="2"/>
有些tag還接受not-null屬性(用來(lái)在表字段上生成NOT NULL約束)和unique屬性(用來(lái)在表字段上生成UNIQUE約束)。
- <many-to-one name="bar" column="barId" not-null="true"/>
- <element column="serialNumber" type="long" not-null="true" unique="true"/>
unique-key屬性可以對(duì)成組的字段指定一個(gè)***鍵約束(unique key constraint)。目前,unique-key屬性指定的值在生成DDL時(shí)并不會(huì)被當(dāng)作這個(gè)約束的名字,它們只是在用來(lái)在映射文件內(nèi)部用作區(qū)分的。
- <many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/>
- <property name="employeeId" unique-key="OrgEmployee"/>
index屬性會(huì)用對(duì)應(yīng)的字段(一個(gè)或多個(gè))生成一個(gè)index,它指出了這個(gè)index的名字。如果多個(gè)字段對(duì)應(yīng)的index名字相同,就會(huì)生成包含這些字段的index。
- <property name="lastName" index="CustName"/>
- <property name="firstName" index="CustName"/>
foreign-key屬性可以用來(lái)覆蓋任何生成的外鍵約束的名字。
- <many-to-one name="bar" column="barId" foreign-key="FKFooBar"/>
很多映射元素還接受
- <property name="name" type="my.customtypes.Name"/>
- <column name="last" not-null="true" index="bar_idx" length="30"/>
- <column name="first" not-null="true" index="bar_idx" length="20"/>
- <column name="initial"/>
- < SPAN>property>
default屬性為字段指定一個(gè)默認(rèn)值 (在保存被映射的類的新實(shí)例之前,你應(yīng)該將同樣的值賦于對(duì)應(yīng)的屬性)。
- <property name="credits" type="integer" insert="false">
- <column name="credits" default="10"/>
- < SPAN>property>
- <version name="version" type="integer" insert="false">
- <column name="version" default="0"/>
- < SPAN>property>
sql-type屬性允許用戶覆蓋默認(rèn)的Hibernate類型到SQL數(shù)據(jù)類型的映射。
- <property name="balance" type="float">
- <column name="balance" sql-type="decimal(13,3)"/>
- < SPAN>property>
check屬性允許用戶指定一個(gè)約束檢查。
- <property name="foo" type="integer">
- <column name="foo" check="foo > 10"/>
- property>
- <class name="Foo" table="foos" check="bar < 100.0">
- ...
- <property name="bar" type="float"/>
- class>
【編輯推薦】