1

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);
    }
}
  1. I get a list of teacher with a named query with the Entity Manager within a EJB context.
  2. Then I create a new ArrayList with the result list, since the result list returned by JPA is read-only.
  3. 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 new ArrayList to the field when it's null. It seems that the students field is modifiable. But other fields such as name is modifiable.

I have googled but found nothing. Hope somebody have an idea about this. Thanks a lot.

BlueMice
  • 333
  • 4
  • 15
  • Every field there is modifiable, also the list of students. You get the NullPointerException because of other things. – V G Dec 18 '13 at 09:02

2 Answers2

1

Remove the S at the end from one stundent to add him.

this.students.add(student);

Big Bad Baerni
  • 996
  • 7
  • 21
  • Oh, I am very sorry. This is my fault because of my carelessness, but not the answer of this question. Thanks:-) BTW, I have corrected the spelling error. – BlueMice Dec 19 '13 at 01:41
1

In addition to Big Bad Baerni response, ensure that your student have the teacher property specified as student is the owner of the relationship here.

public void addStudents(Student student) {
    if(this.students == null){
        this.students = new ArrayList<Student>();
    }
    student.setTeacher(this)
    this.students.add(student);
}

See In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

I don't know your domain but IMHO, there should be a manyToMany relationship here

Community
  • 1
  • 1
Gab
  • 7,869
  • 4
  • 37
  • 68