I use Java and Hibernate to save my entities in database but it's not working as needed. I have a entity Entreprise :
@Entity
public class Entreprise{
@Id
private long identifier;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Person> persons;
...
// getters and setters
}
Here the Person entity which a super class of other entities:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person{
@Id
private long identifier;
@Column
private String name;
...
// constructors,getter and setter
}
And my two subclasses :
@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
}
Here my method to save the entity in the database :
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);
But in the database, the insert was just made in the table Entreprise and Person. Nothing was inserted in the table Employed. I don't know why if someone could explain me, please ?
I try the following code does not also work :
Employed employed = new Employed();
employed.setActualJob("electrician");
employed.setName("John");
Entreprise myEntreprise = new Entreprise();
entreprise.getPersons().addPerson(employed);
entrepriseDao.save(entreprise);
I don't understand why even if i use the subclass to set data it does not work.
Here is the ddl
Hibernate: insert into Entreprise_Person (Entreprise_identifier, person_identifier) values (?, ?);
You are adding a person reference to the enterprise´s list:
entreprise.getPersons().addPerson(person);
Doing that, you add only the person´s data, not the extended employed's data. You should add the employed object instead.
Try adding @PrimaryKeyJoinColumn(name = "YOUR_SUBCLASS_ID_FIELD_THAT_WILL_MATCH_THE_SUPERCLASS_ID_FIELD")
to all subclasses.
The subclasses need identifiers also, this is how they link to their superclass record.
@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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.