My entities are as follows:
@Entity
@Table(name="`surveys`")
@Inheritance
@DiscriminatorColumn(name="`type`")
public abstract class Survey implements Serializable, Comparable<Survey> {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
[...]
}
Above abstract Survey can have two kinds of concrete class:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorValue(value="SV")
public class SupervisorSurvey extends Survey implements Serializable {
@OneToOne(mappedBy="supervisorSurvey",cascade=CascadeType.ALL)
private SurveyPair surveyPair;
[...]
}
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorValue(value="US")
public class UserSurvey extends Survey implements Serializable {
@OneToOne(mappedBy="userSurvey",cascade=CascadeType.ALL)
private SurveyPair surveyPair;
[...]
}
Then an instance of SurveyPair grabs one of both kinds:
@Entity
@Table(name="`surveypairs`")
public class SurveyPair implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToOne
@JoinColumn(name="`userSurveyId`",unique=true)
private UserSurvey userSurvey;
@OneToOne
@JoinColumn(name="`supervisorSurveyId`",unique=true)
private SupervisorSurvey supervisorSurvey;
}
Now the problem: after I create the objects like this:
// survey pair
SurveyPair surveyPair = new SurveyPair(reference);
// user side
UserSurvey usSurvey = new UserSurvey(user);
usSurvey.setSurveyPair(surveyPair);
surveyPair.setUserSurvey(usSurvey);
// supervisor side
SupervisorSurvey svSurvey = new SupervisorSurvey(Application.getLoggedUser(), user);
svSurvey.setSurveyPair(surveyPair);
surveyPair.setSupervisorSurvey(svSurvey);
SurveyInput.getInstance().persist(surveyPair);
the above call to persist:
JPAHelper db = new JPAHelper();
EntityManager em = db.getEntityManager();
em.getTransaction().begin();
em.persist(surveyPair.getUserSurvey());
em.persist(surveyPair.getSupervisorSurvey());
em.persist(surveyPair);
em.getTransaction().commit();
em.close();
inserts the SurveyPair correctly (foreign IDs column values to UserSurvey and SupervisorSurvey are not null), but the UserSurvey and SupervisorSurvey are inserted with NULL IDs.
Why does this happen? If I debug the code just after the persist method, I can inspect the IDs of the object instances and they result to be actually populated.