I'm trying to create an app using spring boot for practicing my java skills, but I faced with small and stupid problem. I created one to many relationship with UserEntity and LessonEntity. And when I try to add lesson to UserEntity set - nothing is happening. The relation doesn't work.
Here's my code:
UserEntity.java
@Entity
@Table(name = "users", schema = "working")
@Getter @Setter
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String firstName;
private String lastName;
private String patronymic;
@Column(unique = true)
private String phoneNumber;
@Column(unique = true)
private String email;
private String password;
private String state;
@OneToMany(mappedBy = "teacher", cascade = CascadeType.ALL)
private Set<LessonEntity> lessons;
}
LessonEntity.java
@Entity
@Table(name = "lessons", schema = "working")
@Getter @Setter
public class LessonEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@ManyToOne
@JoinColumn(name = "teacher_id")
private UserEntity teacher;
}
And here's the code, where I try to add lesson to user:
public void singUpForLesson(UserEntity user, SingUpForLessonModel singUpForLessonModel)
throws UserNotFoundException {
UserEntity teacher = userRepo.findById(singUpForLessonModel.getTeacherId()).orElseThrow(UserNotFoundException::new);
LessonEntity lesson = new LessonEntity();
teacher.getLessons().add(lesson);
lessonRepo.save(lesson);
userRepo.save(teacher);
}
And here's what I see after saving teacher and lesson:
So what can be the problem? If you know, please tell me, I'd really appreciate it!
With a bidirectional relationship you have possibly contradicting information about the state of your relation ship.
This is actually the case in your scenario: The UserEntity
has a additional LessonEntity
, but the LessonEntity
doesn't have a properly set teacher
attribute.
You tell JPA with the mappedBy
attribute which one to use.
This you set to teacher
, i.e. LessonEntity.teacher
which is still empty.
To fix this set the teacher
attribute in your LessonEntity
properly.
You can do this manually, in the setter, and I believe Hibernate has a feature to do this automatically for you.
The alternative, which I would prefer is to not have bidirectional relationships at all.