Video in progress
How do you preserve encapsulation in a JPA entity when Hibernate asks for setters and an empty constructor?
Hibernate doesn't require public setters: if you use field access, it fills the fields with reflection. A protected empty constructor is enough. Expose collections to the outside as unmodifiable and make changes through domain methods.
📖 Answer
@Entity
public class Course {
@Id @GeneratedValue
private Long id;
private String title;
@Enumerated(EnumType.STRING)
private CourseStatus status;
@OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Lesson> lessons = new ArrayList<>();
protected Course() { } // for JPA only
public Course(String title) {
this.title = requireText(title);
this.status = CourseStatus.DRAFT;
}
public void addLesson(String name) {
if (status == CourseStatus.ARCHIVED) throw new IllegalStateException();
lessons.add(new Lesson(this, name)); // the bidirectional link is set in one place
}
public List<Lesson> lessons() { return Collections.unmodifiableList(lessons); }
public void publish() { ... }
}
What to watch for:
- If
@Idis on the field, it is field access; you can name the getters whatever you like, and Hibernate doesn't call them. - Don't reassign the collection field (
this.lessons = newList): Hibernate tracks its ownPersistentBag, and replacing it causes errors withorphanRemoval. unmodifiableListprovides a view, and lazy loading still works.- Only a domain method should set the bidirectional association (
lesson.courseandcourse.lessons), otherwise one side gets forgotten. - Don't generate
equals/hashCodeover all fields with Lombok's@Data: it loads the lazy collection and breaksHashSetwhen the ID changes.
If MapStruct or Jackson asks for setters, they should work with DTOs, not with the entity.
Sign up to mark studied questions and save your progress.