posted 13 years ago
Hi,
I think I don't understand very well how the OneToMany bidirectional relations work in JPA.
In the database I have the following tables/records
Professor(ID INTEGER,DEPARTMENT_ID INTEGER)
Select * from Professor
ID |DEPARTMENT_ID
-----------------------
1 |1
Department(ID INTEGER)
Select * from Department
ID
---
1
My Entities are:
@Entity
public class Department {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@OneToMany(mappedBy="department")
private Collection<Professor> employees;
public Department() {
employees = new ArrayList<Professor>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Collection<Professor> getProfessors() {
return employees;
}
}
@Entity
public class Professor {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@ManyToOne
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
When I execute
Query selectDepartment= em.createQuery("SELECT d from Department d");
Department department = (Department)selectDepartment.getSingleResult();
Collection<Professor> professors = department.getProfessors();
I get an empty collection
I was expecting to get a collection with 1 element. What am I missing here?
Thank you if you reached this far.
Nuno