美文网首页
Hibernate 实现 JPA 对象关系模型之继承映射策略TP

Hibernate 实现 JPA 对象关系模型之继承映射策略TP

作者: 圈圈_Emily | 来源:发表于2019-12-30 15:38 被阅读0次

原文: https://www.ibm.com/developerworks/cn/java/j-lo-hibernatejpa/

Table-per-class 映射策略:

这种映射策略和连接映射策略很类似,不同的是子类对应的表中要继承根实体 (root entity) 中的属性,根实体 (root entity) 对应的表中也不需要区分子类的列,表之间没有共享的表,也没有共享的列。

清单 10.根实体 (root entity)

@Entity

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

@Table(name="Item_TPC")

public class Item implements Serializable {

   private static final long serialVersionUID = 1L;

   @Id

   @GeneratedValue(strategy = GenerationType.AUTO)

   private Long id;

   private String title;

   private Float price;

   private String decription;

    // Getters and Setters

}

Item 根实体在 @Inheritance 注解中指定使用 TABLE_PER_CLASS 映射策略。

清单 11.Magazine 实体 (entity)

@Entity

public class Magazine extends Item {

   private String isbn;

   private String publisher;

    // Getters and Setters

}

清单 12.Phone 实体 ( entity)

@Entity

public class Phone extends Item {

   private String factory;

   private Float DurationTime;

    // Getters and Setters

}

Magazine 和 Phone 子实体没有任何变化。图 6 是对应的 ER 图,从图中可以看出,不同的子实体对应的表中,不仅有自己的属性,还包含了从根实体继承而来的属性,这点与 Joined 映射策略不同,Joined 映射策略中,子实体对应的表中不包含根实体的属性。

图 6. 映射的 ER 图

重写根实体的属性

因为每个子实体对应的表中都继承了根实体中的属性,为了区分可以使用 @AttributeOverride 注解来修改根实体中的属性在不同的子实体中的对应的列名。

清单 13.Magazine 实体 (entity)

@Entity

@AttributeOverrides({

   @AttributeOverride(name="id",  column=@Column(name="Magazine_id")),

   @AttributeOverride(name="title",  column=@Column(name="Magazine_title")),

   @AttributeOverride(name="description", column=@Column(name="Magazine_desc")),

})

public class Magazine extends Item {

   private String isbn;

   private String publisher;

   // Getters and Setters

}

Magazine 实体将从 Item 根实体中继承而来的 id、title、description 属性分别重写为 Magazine_id、Magazine_title 和 Magazine_desc。

清单 14.Phone 实体 ( entity)

@Entity

@AttributeOverrides({

   @AttributeOverride(name="id", column=@Column(name="Phone_id")),

   @AttributeOverride(name="title", column=@Column(name="Phone_title")),

   @AttributeOverride(name="description",column=@Column(name="Phone_desc")),

})

public class Phone extends Item {

   private String factory;

   private Float DurationTime;

    // Getters and Setters

}

Phone 实体将从 Item 根实体中继承而来的 id、title、description 属性分别重写为 Phone _id、Phone _title 和 Phone_desc。

从图 7 就可以看出,根实体中的属性,在子实体中的列名已经被相应地修改了。

图 7. 映射的 ER 图

相关文章

网友评论

      本文标题:Hibernate 实现 JPA 对象关系模型之继承映射策略TP

      本文链接:https://www.haomeiwen.com/subject/vudmoctx.html