我有以下兩個Hiberante物體:
Person
Animal
它們具有共享欄位/列,例如:name, age等,但是每個主鍵 id 欄位的命名不同,例如有person_id和animal_id
@Entity
@Table(name = "person")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty
@Column(name = "person_id")
private Integer person_id;
// all below fields are generic in all the entities
@JsonProperty
@Column(name = "name")
private String name;
@JsonProperty
@Column(name = "age")
private String age;
}
有沒有一種方法可以創建一個包含這些通用name, age等欄位的基本物體超類,然后讓 Person、Animal 和任何新物體擴展這個超物體?
請注意,超類沒有自己的表,所以我不確定我會有什么@Table價值?
我也有主鍵不是全部命名的問題,例如,id因此必須在每個物體中專門指定它們。
uj5u.com熱心網友回復:
如果你不想在你的資料庫中為這個“超級物體”添加一個表(我們稱之為類Being),你仍然可以創建Person并Animal繼承它(Person應該繼承自AnimalBTW),并在上面做公共欄位的映射特性:
public abstract class Being {
private Integer id;
private String name;
// ...
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//...
}
@Entity
@Table(name = "person")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person extends Being {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty
@Column(name = "person_id")
public Integer getId() {
return super.getId();
}
public void setId(Integer id) {
super.setId(id);
}
// all below fields are generic in all the entities
@JsonProperty
@Column(name = "name")
public String getName() {
return super.getName();
}
public void setName(String name) {
super.setName(name);
}
//...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389170.html
上一篇:架構整潔之道:設計模式
