I have a hierarchy of classes like next:
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name="Person")
public class Person implements Serializable{
@Id
@Column(name = "PersonID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
}
@Entity
@Table(name="Student")
@PrimaryKeyJoinColumn(name="PersonID")
public class Student extends Person{
}
@Entity
@Table(name="Bachelor")
@PrimaryKeyJoinColumn(name="PersonID")
public class Bachelor extends Student{
@OneToMany(mappedBy = "bachelor", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<BachelorExam> exams;
}
@Entity
@Table(name="Exam")
public class Exam implements Serializable {
@Id
@Column(name = "ExamID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
}
@Entity
@Table(name="BachelorExam")
public class BachelorExam implements Serializable {
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "PersonID_FK", referencedColumnName = "PersonID")
private Bachelor bachelor;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "ExamID_FK", referencedColumnName = "ExamID")
private Exam exam;
}
I want to get users (regular student or bachelor) from appropriate table by ID using generic method like next:
<T extends Person> T getStudentById(Long studentId);
This method can be something like
public <T extends Person> T getUserById(Long personId) {
List<Class<?>> studentTypes = new LinkedList<>();
studentTypes.add(Student.class);
studentTypes.add(Bachelor.class);
for (Class aClass : studenTypes) {
List<T> results = getDatabaseProvider().getDataFromDatabase(String.format("select u %s as u " +
"where u.userId = '%d'", aClass.getName(), userId));
return results.get(0);
}
}
The problem is that when I save a bachelor object in database, hibernate also saves bachelor's id to 'Student' table so when I get data from database going through whole list of inherited classes, query returns record from table Bachelor and also record from table Student, because both contain required student ID.
I've tried to use InheritanceType Table_Per_class but in this case hibernate doesn't create foreign key for bachelor in table BachelorExam.
How can I receive only records from table Bachelor by id?
Thanks!