Hello, I am making the link tables on Hibernate, one teacher to many students.
Teacher:
@Entity @Table(name = "teacher") public class Teacher implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "name") private String name; @OneToMany(mappedBy = "teacher", cascade = CascadeType.ALL) private Set<Pupil> pupils = new HashSet<>(); // геттеры сеттеры }
Pupil:
@Entity @Table(name = "pupil") public class Pupil implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id ; @Column(name = "name") private String name; @ManyToOne() @JoinColumn(name = "teacher_id") private Teacher teacher; }
Then I create a teacher and a couple of students, put the students in the teacher and save the teacher. I.e:
// сервис ObjectDao objectDao = new ObjectDao(); // создаю учителя Teacher teacher = new Teacher(); teacher.setName("teacher name"); // создаю ученика Pupil pupil = new Pupil(); pupil.setName("pupil name"); // кладу ученика в учителя teacher.getPupils().add(pupil); // сохраняю учителя. objectDao.saveObject(teacher);
Result:
mysql> select * from teacher; +----+--------------+ | id | name | +----+--------------+ | 1 | teacher name | +----+--------------+ mysql> select * from pupil; +----+------------+------------+ | id | name | teacher_id | +----+------------+------------+ | 1 | pupil name | NULL | +----+------------+------------+
Can you please tell me why my student teacher ID is null?