如果您有幾個表格,當中有一些類似的欄位,例如T_USER1有name欄位與age欄位,而T_USER2也有name欄位與age欄位,按照正常的作法,您也許會為兩個表格分別設計User1與User2類別來加以對應。
然而透過entity-name的屬性設定,您可以將一個類別對應至多個表格,例如:
- User.hbm.xml
<?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="onlyfun.caterpillar.User"
entity-name="User1Entity"
table="T_USER1">
<id name="id" column="id" type="long">
<generator class="native"/>
</id>
<property name="name" column="name" />
<property name="age" column="age" />
</class>
<class name="onlyfun.caterpillar.User"
entity-name="User2Entity"
table="T_USER2">
<id name="id" column="id" type="long">
<generator class="native"/>
</id>
<property name="name" column="name" />
<property name="age" column="age"/>
</class>
</hibernate-mapping>
在映射文件中,T_USER1與T_USER2的映射類別都是User類別,藉由entity-name的不同,可以知道該將資料儲存至哪一個表格:
User user = new User();
user.setName("caterpillar");
user.setAge(new Long(30));
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx= session.beginTransaction();
// 儲存至T_USER1
session.save("User1Entity", user);
tx.commit();
session.close();
user = new User();
user.setName("justin");
user.setAge(new Long(32));
session = HibernateUtil.getSessionFactory().openSession();
tx= session.beginTransaction();
// 儲存至T_USER2
session.save("User2Entity", user);
tx.commit();
session.close();
查詢時也是藉由指定entity-name來取得對應的表格資料,並封裝為User實例,例如以下會取得T_USER1中的資料:
User user = (User) session.load("User1Entity", new Long(1));