これは私のエンティティ定義です:
@EmbeddedId
private TeacherPK id;
//bi-directional many-to-one association to Exam
@OneToMany(mappedBy="teacher", fetch=FetchType.LAZY)
private List<Exam> exams;
//bi-directional many-to-one association to Subject
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="fkSubject", nullable=false, insertable=false, updatable=false)
private Subject subject;
//bi-directional many-to-one association to Professor
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="fkProfessor1", referencedColumnName = "idProfessor", nullable=false, insertable=false, updatable=false)
private Professor professor1;
//bi-directional many-to-one association to Professor
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="fkProfessor2", referencedColumnName = "idProfessor")
private Professor professor2;
//bi-directional many-to-one association to Professor
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="fkProfessor3", referencedColumnName = "idProfessor")
private Professor professor3;
次に、professor1.id、professor2.id、professor3.id のいずれかが指定された ID と等しいすべての教師を取得します。
public List<Teacher> getTeacherByProfessor(Professor professor) {
Query query = em.createQuery("SELECT teacher FROM Teacher teacher WHERE teacher.professor1.idProfessor=:idProfessor OR " +
"(teacher.professor2 IS NOT NULL AND teacher.professor2.idProfessor=:idProfessor) OR (teacher.professor3 IS NOT NULL AND teacher.professor3.idProfessor=:idProfessor)");
query.setParameter("idProfessor", professor.getIdProfessor());
return (List<Teacher>) query.getResultList();
}
しかし、このメソッドを実行すると、3 つの教授すべてが定義されているオブジェクトのみが取得されます。Professor3 が null の場合、そのオブジェクトは結果に含まれません。エンティティ定義からわかるように、professor1 だけは NULL にできません。
編集:
基本的には、このSQL文をJPQL文で実行したい(たとえばset 7)
SELECT * FROM Teacher WHERE fkProfessor1 = 7 OR fkProfessor2 = 7 OR fkProfessor3 = 7