如果要在所需表中保存公共字段,则意味着假设您拥有A类和B类,并且具有一些通用文件(例如created_by,updated_by),并且希望将field1,field2保存在两个实体中:IN数据库级:
query> select * from A;+----++------------------------+| id | created_by | updated_by |+----+------------+------------+| 3 | xyz | abc |+----+------------+------------+query> select * from B; +----++------------------------+| id | created_by | updated_by |+----+------------+------------+| 3 | xyz | abc |+----+------------+------------+
对于这种类型的结构,您应该使用@MappedSuperclass,就像@Dragan Bozanovic建议的那样
但是,如果您需要“父子”关系并要为每个类生成表,则可以使用@Inheritance(strategy =
InheritanceType.TABLE_PER_CLASS)来为每个类创建表,例如:假设您有2个类Payment和CreditCard,Payment是CreditCard的父类。
@Entity@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)public class Payment { @Id @GeneratedValue(strategy = GenerationType.TABLE) private int id; @Column(nullable = false) private double amount; public int getId() { return id; } public void setId(int id) { this.id = id; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; }}@Entitypublic class CreditCard extends Payment {private String ccNumber;private Date expireDate; public String getCcNumber() { return ccNumber; } public void setCcNumber(String ccNumber) { this.ccNumber = ccNumber; } public Date getExpireDate() { return expireDate; } public void setExpireDate(Date expireDate) { this.expireDate = expireDate; }}
现在,您将保存日期:
public class TestConcreteClasses { public static void main(String[] args) { Payment payment = new Payment(); payment.setAmount(52.6); createData(payment); CreditCard creditCard = new CreditCard(); creditCard.setAmount(10); creditCard.setCcNumber("2536985474561236"); creditCard.setExpireDate(new Date()); createData(creditCard); } private static void createData(Payment instance) { Session session = HibernateUtil.getSession(); session.beginTransaction(); session.save(instance); session.getTransaction().commit(); }}
然后数据将保存为
query> select * from Payment;+----+--------+| id | amount |+----+--------+| 1 | 52.6 |+----+--------+1 row in set (0.00 sec) select * from CreditCard;+----+--------+------------------+---------------------+| id | amount | ccNumber | expireDate |+----+--------+------------------+---------------------+| 2 | 10 | 2536985474561236 | 2017-03-12 14:10:15 |+----+--------+------------------+---------------------+1 row in set (0.00 sec)
hibernate中使用了3种类型的继承,这是用于继承的hibernate文档
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/InheritanceType.html,您应该根据以下条件进行选择您的要求。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)