I have a JPA Entity with definition like this:
@Entity
@Table(name = "JPA_TEACHER")
public class Teacher implements ITeacher{
@Id
private String id;
@Column(name = "NAME")
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name="TEACHER_ID", referencedColumnName="ID")
private List<Student> students;
public Teacher() {
super();
}
public Teacher(String name) {
super();
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public void addStudents(Student student) {
if(this.students == null){
this.students = new ArrayList<Student>();
}
this.students.add(student);
}
}
- I get a list of teacher with a named query with the Entity Manager within a EJB context.
- Then I create a new
ArrayList
with the result list, since the result list returned by JPA is read-only. - I try to add students to the students field of some teachers whose students field is null. Then I get a
NullPointException
, no matter that I have tried to assign a newArrayList
to the field when it's null. It seems that the students field is modifiable. But other fields such asname
is modifiable.
I have googled but found nothing. Hope somebody have an idea about this. Thanks a lot.