Home > Back-end >  Jpa OneToMang bidirectional association, many can't save foreign keys
Jpa OneToMang bidirectional association, many can't save foreign keys

Time:09-29

Jpa bidirectional associative table (the Teacher - & gt; Student) encounter a problem when saving, save the Student (s) through a database query and set its associated the Teacher (already exists in the database, with id 1). Try a number of ways, to keep foreign key teacherId, please action:)

Error message: detached entity passed to persist: com. Ld. The entity. The Teacher, (seemingly object within the loop contains),

The code is as follows:

Entity class: the Teacher
@ the Entity
@ Data
Public class the Teacher {
@ Id
@ GeneratedValue (strategy=GenerationType. IDENTITY)
Long id;
String name;

The @onetomany (mappedBy="the teacher", cascade=CascadeType. ALL)
Private List Students;
}

Entity classes: Student
@ the Entity
@ Data
Public class Student {
@ Id
@ GeneratedValue (strategy=GenerationType. IDENTITY)
private Long id;
private String name;
private Integer age;

@ Transient
Private Long teacherId;

@ ManyToOne (cascade=CascadeType. ALL the fetch=FetchType. LAZY)
@ JoinColumn (name="teacherId")
Private the Teacher the Teacher;
}

The test class:
@ Test
Void addStudent () {
Student Student=new Student ();
Student. SetAge (14);
Student. Elegantly-named setName (" small ");
The Teacher. The Teacher=teacherDao findById (1 l). The get ();
Student. SetTeacher (the teacher);

StudentDao. Save (student);
}
  • Related