eclipse + JBoss 5 + EJB3開發指南(10)

來源:互聯網
上載者:User

通過繼承實體Bean,將單個表映射成多個表(單表策略,SINGLE_TABLE)

如果以前使用過EJB1.x或EJB2.x的實體Bean,會發現無法通過繼承實體Bean將單個表分成多表。而在 EJB3中,我們很容易實現這個功能。先看看圖1所示的表結構和記錄。

圖1   t_accounts表的結構和記錄

在t_accounts表中,有一個account_type欄位。這個欄位是一個長度為1的String類型欄位。只能取兩 個值:C和S。如果該欄位值為C,表示活期帳戶(CheckingAccount),如果該欄位值為S,表示儲蓄存款 帳戶(SavingsAccount)。t_accounts表的前三個欄位(account_id、balance和account_type)是活期 帳戶和儲蓄存款帳戶都需要的,而interestrate只對儲蓄存款帳戶有意義,overdraftlimit只對活期帳戶 有意義。因此,我們可以將t_accounts表分成兩個表,當account_type的值為C時和S時各為一個表。

如果使用EJB3的實體Bean,可以先編寫一個Account類來封裝t_accounts的前三個欄位,代碼如下:

package entity;import javax.persistence.Column;import javax.persistence.DiscriminatorColumn;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Inheritance;import javax.persistence.InheritanceType;import javax.persistence.Table;@Entity@Table(name="t_accounts")@Inheritance(strategy=InheritanceType.SINGLE_TABLE)@DiscriminatorColumn(name="account_type")public class Account{    protected String id;    protected float balance;    protected String type;    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name="account_id")    public String getId()    {        return id;    }    public void setId(String id)    {        this.id = id;    }    public float getBalance()    {        return balance;    }    public void setBalance(float balance)    {        this.balance = balance;    }    @Column(name="account_type",insertable=false, updatable=false)    public String getType()    {        return type;    }    public void setType(String type)    {        this.type = type;    }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.