[英]How to save in database a hierarchy class?
我使用Java和Hibernate將我的實體保存在數據庫中,但是無法按需工作。 我有一個實體Entreprise:
@Entity
public class Entreprise{
@Id
private long identifier;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Person> persons;
...
// getters and setters
}
這里的Person實體是其他實體的超類:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person{
@Id
private long identifier;
@Column
private String name;
...
// constructors,getter and setter
}
還有我的兩個子類:
@Entity
public class Employed extends Person{
@Column
private String actualJob;
// constructors,getter and setter
}
@Entity
public class Unemployed extends Person{
@Column
private String lastJob;
// constructors,getter and setter
}
這是我將實體保存在數據庫中的方法:
Person person = new Employed();
person.setName("John");
Employed employed = (Employed) person;
employed.setActualJob("electrician");
Entreprise myEntreprise = new Entreprise();
entreprise.getPersons().addPerson(person);
entrepriseDao.save(entreprise);
但是在數據庫中,插入只是在表Entreprise和Person中進行的。 未在“已使用”表中插入任何內容。 我不知道為什么有人可以向我解釋?
我嘗試以下代碼也不起作用:
Employed employed = new Employed();
employed.setActualJob("electrician");
employed.setName("John");
Entreprise myEntreprise = new Entreprise();
entreprise.getPersons().addPerson(employed);
entrepriseDao.save(entreprise);
我不明白為什么即使我使用子類來設置數據也不起作用。
這是DDL
Hibernate: insert into Entreprise_Person (Entreprise_identifier, person_identifier) values (?, ?);
您正在將個人參考添加到企業列表中:
entreprise.getPersons().addPerson(person);
這樣,您僅添加人員的數據,而不添加擴展員工的數據。 您應該改為添加所使用的對象。
嘗試將@PrimaryKeyJoinColumn(name = "YOUR_SUBCLASS_ID_FIELD_THAT_WILL_MATCH_THE_SUPERCLASS_ID_FIELD")
到所有子類。
子類也需要標識符,這就是它們鏈接到其超類記錄的方式。
@Entity
@PrimaryKeyJoinColumn(name = "identifier")
public class Employed extends Person{
@Id
private long identifier;
@Column
private String actualJob;
// constructors,getter and setter
}
@Entity
@PrimaryKeyJoinColumn(name = "identifier")
public class Unemployed extends Person{
@Id
private long identifier;
@Column
private String lastJob;
// constructors,getter and setter
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.