从上面的代码可以看出,只使用了@Inheritance对实体Bean进行注释。下面编写MyCheckingAccount和MySavingsAccount类的代码:
MyCheckingAccount类的代码:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> package entity; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = " t_checkingaccount " ) // 指定与Account类共享的主键名 @PrimaryKeyJoinColumn(name = " account_id " ) public class MyCheckingAccount extends Account { private double overdraftLimit; public MyCheckingAccount() { // 为account_type字段赋默认值 setType( " C " ); } @Column(name = " overdraft_limit " ) public double getOverdraftLimit() { return overdraftLimit; } public void setOverdraftLimit( double overdraftLimit) { this .overdraftLimit = overdraftLimit; } }MySavingsAccount类的代码:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> package entity; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = " t_savingsaccount " ) @PrimaryKeyJoinColumn(name = " account_id " ) public class MySavingsAccount extends Account { private double interestRate; public MySavingsAccount() { // 为account_type字段赋默认值 setType( " S " ); } @Column(name = " interest_rate " ) public double getInterestRate() { return interestRate; } public void setInterestRate( double interestRate) { this .interestRate = interestRate; } }
在上面的代码中使用构造方法来初始化了t_myaccounts表的account_type字段的值。 可以使用下面的代码进行测试:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> System.out.println(((MyCheckingAccount)em.createQuery( " fromMyCheckingAccountwhereid=12 " ) .getSingleResult()).getBalance()); MyCheckingAccountca = new MyCheckingAccount(); ca.setBalance( 342 ); ca.setOverdraftLimit( 120 ); em.persist(ca); MySavingsAccountsa = new MySavingsAccount(); sa.setBalance( 200 ); sa.setInterestRate( 321 ); em.persist(sa); 下一篇: eclipse + JBoss 5 + EJB3开发指南(12):使用命名查询执行JPQL 国内最棒的Google Android技术社区(eoeandroid),欢迎访问! 《银河系列原创教程》发布 《Java Web开发速学宝典》出版,欢迎定购 相关资源:敏捷开发V1.0.pptx