Video in progress

Strong Middle 🧱 OOP and SOLID

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 @Id is 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 own PersistentBag, and replacing it causes errors with orphanRemoval.
  • unmodifiableList provides a view, and lazy loading still works.
  • Only a domain method should set the bidirectional association (lesson.course and course.lessons), otherwise one side gets forgotten.
  • Don't generate equals/hashCode over all fields with Lombok's @Data: it loads the lazy collection and breaks HashSet when the ID changes.

If MapStruct or Jackson asks for setters, they should work with DTOs, not with the entity.