內含 Component 的集合


假設您建立了以下的表格:
create table email (
    id bigint not null,
    address varchar(255)
)

create table user (
    id bigint not null auto_increment,
    name varchar(255),
    primary key (id)
)

alter table email
    add index id (id),
    add constraint id
    foreign key (id)
    references user (id)


一個user可以有多個email,但不可重複,這可以使用 Set 來映射,在對應的物件方法,您可以如下設計物件:
package onlyfun.caterpillar;

import java.util.Set;

public class User {
    private Long id;
    private Set emails;
    ....
}

假設您原先預定在Set中儲存的是String型態,而後設計時考慮獨立設計一個MailAddress類別,而Set中將儲存MailAddress的 實例,例如:
  • User.java
package onlyfun.caterpillar;

import java.util.Set;

public class User {
private Long id;
private String name;
private Set emails;

// 必須要有一個預設的建構方法
// 以使得Hibernate可以使用Constructor.newInstance()建立物件
public User() {}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set getEmails() {
return emails;
}

public void setEmails(Set emails) {
this.emails = emails;
}

public void addEmail(MailAddress mailAddress) {
this.emails.add(mailAddress);
}

public void removeEmail(MailAddress mailAddress) {
this.emails.remove(mailAddress);
}
}

  • MailAddress.java
package onlyfun.caterpillar;

public class MailAddress {
private String address;

public MailAddress() {}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public void sendMail() {
System.out.println("Send mail to " + address);
}
}

在映射文件方面,可以使用<composite-element>來為MailAddress作映射,如下:
  • 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" table="user">
<id name="id" column="id">
<generator class="native"/>
</id>

<property name="name" column="name"/>

<set name="emails" table="email">
<key column="id" foreign-key="id"/>
<composite-element class="onlyfun.caterpillar.MailAddress">
<property name="address" column="address"/>
</composite-element>
</set>
</class>
</hibernate-mapping>

您可以如下儲存物件:
User user = new User();
user.setName("caterpillar");
       
user.setEmails(new HashSet());
MailAddress mailAddress = new MailAddress();
mailAddress.setAddress("caterpillar.onlyfun@gmail.com");
user.addEmail(mailAddress);
       
mailAddress = new MailAddress();
mailAddress.setAddress("caterpillar.onlyfun@yahoo.com");
user.addEmail(mailAddress);
       
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();

則資料庫中會儲存如下的資料:
mysql> select * from user;
+----+-------------+
| id    | name        |
+----+-------------+
|  1    | caterpillar |
+----+-------------+
1 row in set (0.00 sec)

mysql> select * from email;
+----+-------------------------------------------+
| id    | address                                            |
+----+-------------------------------------------+
|  1    | caterpillar.onlyfun@yahoo.com  |
|  1    | caterpillar.onlyfun@gmail.com    |
+----+-------------------------------------------+
2 rows in set (0.00 sec)


在查詢時,address表格的資料會封裝為MailAddress的實例,一個範例如下:
Session session = HibernateUtil.getSessionFactory().openSession();
       
User user = (User) session.load(User.class, new Long(1));
Iterator iterator = user.getEmails().iterator();
while(iterator.hasNext()) {
    MailAddress mailAddress = (MailAddress) iterator.next();
    mailAddress.sendMail();
}
session.close();

如果要實現雙向關係的話,也可以在<composite-element>中加上<parent>標籤,作法類似Component 中的作法,例如:
    ...
        <set name="emails" table="email">
            <key column="id" foreign-key="user_id"/>
            <composite-element class="onlyfun.caterpillar.MailAddress">
                <parent name="user"/>
                <property name="address" column="address"/>
            </composite-element>
        </set>
    ...