ORM and JPA series: 1. Entities and repositories · 2. Entity relationships · 3. The E-Learning schema, DTOs, JSON · 4. Persistence context and N+1 · 5. JPQL, @Transactional, locking
Part 2 explained each kind of relationship on a trimmed-down model; this part applies them to the real schema of the course’s E-Learning pet project: eleven tables, a many-to-many with attributes and a progress table with a composite key. The second half deals with what happens the moment you return those entities from an API: Jackson recursing forever, why the slides reach for @JsonIgnore, and why the right fix is a DTO. Read part 1 (entities, repositories, layers) and part 2 (owning side, mappedBy, cascades) first; I ran every mapping in this post on Hibernate 6.6 with H2.
1. The course’s E-Learning schema and how to map it to JPA
Key idea: each relationship in the schema gets its own mapping: the one-to-many chain uses @ManyToOne on the child table, a one-to-one puts the owning side on the table holding the FK, a plain many-to-many uses @ManyToMany, and a many-to-many with extra columns must become its own entity.
The second ORM lesson presents the full design of the E-Learning pet project, and the homework asks you to map exactly that. (SQL queries on the same model are in the SQL JOIN and GROUP BY exercises.)
1.1. Tables and relationships
erDiagram
USERS ||--o| FULL_NAME : has
USERS ||--o{ USER_ADDRESS : "lives at"
ADDRESS ||--o{ USER_ADDRESS : houses
USERS ||--o{ USER_COURSE : enrolls
COURSE ||--o{ USER_COURSE : "enrolled by"
TEACHER ||--o{ COURSE : teaches
COURSE ||--o{ CHAPTER : contains
CHAPTER ||--o{ LESSON : contains
USER_COURSE ||--o{ USER_COURSE_LESSON : tracks
LESSON ||--o{ USER_COURSE_LESSON : "progress of"
USERS {
bigint id PK
varchar username UK
varchar password
varchar nickname
varchar status
}
FULL_NAME {
bigint id PK
varchar first_name
varchar mid_name
varchar last_name
bigint user_id FK
}
USER_COURSE {
bigint user_id PK,FK
bigint course_id PK,FK
int rating
varchar review
varchar status
}
USER_COURSE_LESSON {
bigint user_id FK
bigint course_id FK
bigint lesson_id FK
varchar status
}
LESSON {
bigint id PK
varchar name
varchar type
varchar url
int sort_order
bigint chapter_id FK
}
ADMIN {
bigint id PK
varchar username UK
varchar password
varchar status
}
| Table | Main columns | Role |
|---|---|---|
user |
id, username (unique), password, nickname, status |
Learners |
full_name |
id, first_name, mid_name, last_name, status, user_id FK |
Dependent side of the one-to-one with user |
admin, teacher |
id, username (unique), password, status |
Admin and teacher accounts, one table each |
course |
id, name, description, status, teacher_id FK |
Teacher 1-n Course |
chapter |
id, name, description, order, status, course_id FK |
Course 1-n Chapter |
lesson |
id, name, description, type, url, order, status, chapter_id FK |
Chapter 1-n Lesson |
user_course |
PK (user_id, course_id), rating, review, status |
User–Course many-to-many with attributes (rating, course progress) |
user_course_lesson |
user_id, course_id, lesson_id, status |
Per-lesson progress of one enrolment |
user_address, address |
(user_id, address_id); country, city, district, street, address_detail |
Plain User–Address many-to-many |
Every table (except the two plain join tables) also has created_date and updated_date. There are three fixed value sets:
statusof the configuration tables (user,admin,teacher,course,chapter,lesson):ACTIVE/INACTIVE.statusofuser_courseanduser_course_lesson:START(default) /PROCESSING/DONE.lesson.type:VIDEO/PDF/DOCX/SLIDE.
1.2. What to fix when following the slides
- Typos on the diagram: the “Tearcher” table and “tearcher_id” column (should be
teacher,teacher_id), the note’s “User_Course_Lession” and “Lession” (should belesson), and the lesson type “SLICE” (should beSLIDE). Copy them as-is and your table names, column names and enum constants are wrong from day one; fixing them later is a migration. - Two names clash with SQL keywords; see the block below.
1.3. Mapping each table
The shared columns (created_date, updated_date) go into a @MappedSuperclass (a parent class holding shared columns that is not an entity itself). Each fixed value set is an enum stored as a string (EnumType.STRING).
| Relationship | Mapping |
|---|---|
| User 1-1 FullName | FullName holds the FK user_id (owning side, unique = true so the database really blocks a second full name for the same user); User has mappedBy = "user", cascade = ALL, orphanRemoval |
| User n-n Address (plain) | @ManyToMany + @JoinTable user_address, as a Set |
| Teacher → Course → Chapter → Lesson | @ManyToOne(fetch = LAZY, optional = false) on the child table; the parent declares a collection only when navigation needs it, and never cascades REMOVE |
| User n-n Course (with attributes) | A UserCourse entity, composite key @EmbeddedId + @MapsId |
| Per-lesson progress | A UserCourseLesson entity: auto-increment id, UNIQUE on the three columns, composite FK to user_course |
Compared with the slides’ code: the slides use private int id and fetch = FetchType.EAGER on the User side. Prefer Long (a null id unambiguously means “not saved yet”) and LAZY on the owning side. The inverse side of a @OneToOne is still loaded eagerly (see the pitfall in section 1.4 of part 2), so if the API rarely needs the full name you can drop the fullName field from User altogether.
Full code: BaseEntity, enums, User, FullName, Address, Course, Lesson
@MappedSuperclass
public abstract class BaseEntity {
@CreationTimestamp
@Column(name = "created_date", updatable = false)
private Instant createdDate;
@UpdateTimestamp
@Column(name = "updated_date")
private Instant updatedDate;
}
public enum Status { ACTIVE, INACTIVE } // configuration tables
public enum ProgressStatus { START, PROCESSING, DONE } // user_course, user_course_lesson
public enum LessonType { VIDEO, PDF, DOCX, SLIDE }
User, FullName (one-to-one) and Address (plain many-to-many):
@Entity
@Table(name = "users")
public class User extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password; // store only a hash (BCrypt), never return it
@Column(length = 50)
private String nickname;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private Status status = Status.ACTIVE;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private FullName fullName;
@ManyToMany
@JoinTable(name = "user_address",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "address_id"))
private Set<Address> addresses = new HashSet<>();
public void setFullName(FullName fullName) { // keep both sides in sync
this.fullName = fullName;
fullName.setUser(this);
}
}
@Entity
@Table(name = "full_name")
public class FullName extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String midName;
private String lastName;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private Status status = Status.ACTIVE;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false, unique = true)
private User user;
}
@Entity
@Table(name = "address")
public class Address {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String country;
private String city;
private String district;
private String street;
private String addressDetail;
@ManyToMany(mappedBy = "addresses")
private Set<User> users = new HashSet<>();
}
The Course and Lesson one-to-many chain:
@Entity
@Table(name = "course")
public class Course extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String name;
@Column(length = 1000)
private String description;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private Status status = Status.ACTIVE;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "teacher_id", nullable = false)
private Teacher teacher;
@OneToMany(mappedBy = "course")
@OrderBy("sortOrder")
private List<Chapter> chapters = new ArrayList<>();
}
@Entity
@Table(name = "lesson")
public class Lesson extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String name;
@Column(length = 1000)
private String description;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private LessonType type;
private String url;
@Column(name = "sort_order", nullable = false)
private int sortOrder;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private Status status = Status.ACTIVE;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "chapter_id", nullable = false)
private Chapter chapter;
}
Teacher (with @OneToMany(mappedBy = "teacher") List<Course> courses), Admin and Chapter (with sortOrder and @ManyToOne Course course) follow the same pattern.
User – Course (many-to-many with attributes): user_course has rating, review and status, so @ManyToMany won’t do (it only manages the two FK columns). Map it as a UserCourse entity with a composite @EmbeddedId, plus @MapsId so the two key columns are also the two FKs (derived identity: the id comes from the associations):
@Embeddable
public class UserCourseId implements Serializable {
private Long userId;
private Long courseId;
protected UserCourseId() {}
public UserCourseId(Long userId, Long courseId) { this.userId = userId; this.courseId = courseId; }
@Override public boolean equals(Object o) {
return o instanceof UserCourseId other
&& Objects.equals(userId, other.userId) && Objects.equals(courseId, other.courseId);
}
@Override public int hashCode() { return Objects.hash(userId, courseId); }
}
@Entity
@Table(name = "user_course")
public class UserCourse extends BaseEntity {
@EmbeddedId
private UserCourseId id;
@MapsId("userId")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@MapsId("courseId")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
private Course course;
private Integer rating;
private String review;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private ProgressStatus status = ProgressStatus.START;
protected UserCourse() {}
public UserCourse(User user, Course course) {
this.id = new UserCourseId(user.getId(), course.getId());
this.user = user;
this.course = course;
}
public void markInProgress() {
if (status == ProgressStatus.START) status = ProgressStatus.PROCESSING;
}
}
Per-lesson progress (user_course_lesson): an auto-increment id is the primary key, and the slides’ three columns sit in a unique constraint. The composite FK (user_id, course_id) points at user_course, so the database also refuses progress rows for a course the user never enrolled in.
UserCourseLesson code and the test run on Hibernate 6.6
@Entity
@Table(name = "user_course_lesson",
uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "course_id", "lesson_id"}))
public class UserCourseLesson extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumns({
@JoinColumn(name = "user_id", referencedColumnName = "user_id"),
@JoinColumn(name = "course_id", referencedColumnName = "course_id")
})
private UserCourse userCourse;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "lesson_id")
private Lesson lesson;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 50)
private ProgressStatus status = ProgressStatus.START;
protected UserCourseLesson() {}
public UserCourseLesson(UserCourse userCourse, Lesson lesson) {
this.userCourse = userCourse;
this.lesson = lesson;
}
public void complete() { this.status = ProgressStatus.DONE; }
}
I ran this mapping on Hibernate 6.6 with H2 (MySQL mode): create a user with a full name and an address, a teacher, a course, a chapter, a lesson, one enrolment and one progress row, then read it back with find(UserCourse.class, new UserCourseId(userId, courseId)).
Hibernate generated the composite PK for user_course, the composite FK from user_course_lesson to user_course, and a UNIQUE on full_name.user_id. With EnumType.STRING it even created an enum('ACTIVE','INACTIVE') column type.
Two more design choices: account tables and composite PK column order
2. Returning entities as JSON: infinite recursion, @JsonIgnore and DTOs
Key idea: bidirectional relationships make Jackson go round in circles while serializing (turning objects into JSON). @JsonIgnore only breaks the cycle; the right fix is mapping entities to DTOs (objects that only carry data out of the API) in the service, while the transaction is open.
2.1. The problem: bidirectional relationships send Jackson round in circles
In the slides’ demo, GET /api/v1/users/{id} returns the User entity directly, and the JSON has full_name nested inside along with an addresses list. To make that work, the slides put @JsonIgnore on FullName.user and Address.users. The reason: Jackson walks every getter/field, so with the bidirectional mapping from section 1.3 it goes User → fullName → user → fullName → ... with no end.
Reproducing exactly that (Hibernate 6.6, Jackson 2.18, entities without @JsonIgnore):
JsonMappingException: Document nesting depth (1001) exceeds the maximum allowed
(1000, from `StreamWriteConstraints.getMaxNestingDepth()`)
(through reference chain: elearn.FullName["user"]->elearn.User["fullName"]->elearn.FullName["user"]->...)
Older Jackson versions have no such depth limit, so the error surfaces as a StackOverflowError, wrapped as JsonMappingException: Infinite recursion (StackOverflowError). Spring returns a 500 to the client.
2.2. The slides’ fix: @JsonIgnore on the back-reference
@Entity
@Table(name = "full_name")
public class FullName {
// ...
@JsonIgnore
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false, unique = true)
private User user;
}
@Entity
@Table(name = "address")
public class Address {
// ...
@JsonIgnore
@ManyToMany(mappedBy = "addresses")
private Set<User> users = new HashSet<>();
}
The cycle is broken: User includes fullName, but fullName no longer contains user. The price:
- One direction is gone from the JSON for good. A
GET /addresses/{id}endpoint can never return the residents, even when that screen needs them. - Every other field goes out. The
@JsonIgnoreversion returned{"id":1,"username":"johndoe","password":"$2a$10$hash","fullName":{"id":1,"lastName":"Doe"}}. Both theUserandTeacherentities in the slides have apasswordcolumn.
2.3. Jackson’s other options
| Option | Where it goes | User JSON (tested) |
Notes |
|---|---|---|---|
@JsonIgnore |
On the back-reference | {"id":1,...,"fullName":{"lastName":"Doe"}} |
Simple; the reverse direction is gone |
@JsonManagedReference / @JsonBackReference |
@JsonManagedReference on the parent, @JsonBackReference on the child |
{"id":1,"fullName":{"lastName":"Doe"}} |
Like @JsonIgnore on output, but on input Jackson restores the back-reference |
@JsonIdentityInfo |
On both classes | {"id":1,"fullName":{"id":7,"lastName":"Doe","user":1}} |
The second time it meets the same object it writes only the id; clients must understand that convention |
| DTO (record) | A separate response class | {"id":1,"username":"johndoe","fullName":{...},"cities":[...]} |
Full control, no Hibernate involvement |
Another error with the same root cause, common when returning entities with LAZY associations:
2.4. The right fix: map to DTOs in the service
public record FullNameResponse(String firstName, String midName, String lastName) {
static FullNameResponse from(FullName f) {
return new FullNameResponse(f.getFirstName(), f.getMidName(), f.getLastName());
}
}
public record AddressResponse(Long id, String country, String city, String district,
String street, String addressDetail) {
static AddressResponse from(Address a) {
return new AddressResponse(a.getId(), a.getCountry(), a.getCity(), a.getDistrict(),
a.getStreet(), a.getAddressDetail());
}
}
public record UserResponse(Long id, String username, String nickname, Status status,
FullNameResponse fullName, List<AddressResponse> addresses) {
static UserResponse from(User u) {
return new UserResponse(u.getId(), u.getUsername(), u.getNickname(), u.getStatus(),
u.getFullName() == null ? null : FullNameResponse.from(u.getFullName()),
u.getAddresses().stream().map(AddressResponse::from).toList());
}
}
public interface UserRepository extends JpaRepository<User, Long> {
@EntityGraph(attributePaths = {"fullName", "addresses"}) // load it all at once, no N+1
Optional<User> findWithDetailsById(Long id);
}
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) { this.userRepository = userRepository; }
@Transactional(readOnly = true)
public UserResponse get(long id) {
return userRepository.findWithDetailsById(id)
.map(UserResponse::from) // map while the transaction is open
.orElseThrow(() -> new UserNotFoundException(id));
}
}
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) { this.userService = userService; }
@GetMapping("/{id}")
public UserResponse get(@PathVariable long id) { return userService.get(id); }
}
- The entities need no Jackson annotations; a DTO is a tree with no cycles, so bidirectional relationships stop mattering.
passwordnever leaves the service.- If you want
snake_caseJSON like the slides (full_name,address_detail): setspring.jackson.property-naming-strategy=SNAKE_CASEor put@JsonPropertyon the DTO fields.
Upgrading to Jackson 3 (Spring Boot 4)
Exercises
The relationships exercise from the ORM lessons, on the E-Learning pet project (another edition of the course uses a hotel management brief with Hotel, Room and Employee; the approach is identical). The full brief is in Hands-on pet project; the exercises on entities, repositories and CRUD are in part 1 of the series.
Exercise 4: Map the relationships of the E-Learning entities and keep building the APIs
Task (paraphrased): add the relationship annotations (1-1, 1-n, n-n) to the entities so they match the foreign keys in the E-Learning schema, then keep building out the data logic behind the APIs.
Solution to Exercise 4: the mapping and three APIs for enrolling, completing a lesson, viewing a user
The mapping part: exactly section 1.3.
User1-1FullName:FullNameholds the FKuser_id(owning side,unique = true),UserhasmappedBy = "user"withcascade = ALL+orphanRemoval, because the name belongs to the user.Teacher1-nCourse1-nChapter1-nLesson:@ManyToOne(fetch = LAZY, optional = false)on the child side, noREMOVEcascade from the parent.Usern-nAddress:@ManyToMany+@JoinTable user_address, as aSet.Usern-nCoursewith attributes: theUserCourseentity with@EmbeddedId+@MapsId.- Progress: the
UserCourseLessonentity, with a composite FK(user_id, course_id)touser_courseand a unique constraint on the three columns.
The API part: three main operations: enrolling in a course, marking a lesson as done, and viewing a user (section 2.4).
@Service
public class LearningService {
private final UserRepository userRepository;
private final CourseRepository courseRepository;
private final LessonRepository lessonRepository;
private final UserCourseRepository userCourseRepository;
private final UserCourseLessonRepository progressRepository;
private final EntityManager entityManager;
// constructor injection omitted for brevity
@Transactional
public EnrollmentResponse enroll(long userId, long courseId) {
UserCourseId id = new UserCourseId(userId, courseId);
if (userCourseRepository.existsById(id)) {
throw new AlreadyEnrolledException(userId, courseId); // → 409
}
Course course = courseRepository.findById(courseId)
.filter(c -> c.getStatus() == Status.ACTIVE)
.orElseThrow(() -> new CourseNotFoundException(courseId)); // → 404
UserCourse enrollment = new UserCourse(userRepository.getReferenceById(userId), course);
entityManager.persist(enrollment); // assigned id: persist instead of save() to skip merge + SELECT
return EnrollmentResponse.from(enrollment);
}
@Transactional
public void completeLesson(long userId, long courseId, long lessonId) {
UserCourse enrollment = userCourseRepository.findById(new UserCourseId(userId, courseId))
.orElseThrow(() -> new NotEnrolledException(userId, courseId));
if (!lessonRepository.existsByIdAndChapterCourseId(lessonId, courseId)) {
throw new LessonNotInCourseException(lessonId, courseId); // lesson isn't part of this course
}
UserCourseLesson progress = progressRepository
.findByUserCourseAndLessonId(enrollment, lessonId)
.orElseGet(() -> progressRepository.save(
new UserCourseLesson(enrollment, lessonRepository.getReferenceById(lessonId))));
progress.complete(); // dirty checking issues the UPDATE on commit
enrollment.markInProgress(); // START → PROCESSING
}
}
public interface LessonRepository extends JpaRepository<Lesson, Long> {
boolean existsByIdAndChapterCourseId(Long lessonId, Long courseId); // lesson.chapter.course.id
}
public interface UserCourseLessonRepository extends JpaRepository<UserCourseLesson, Long> {
Optional<UserCourseLesson> findByUserCourseAndLessonId(UserCourse userCourse, Long lessonId);
}
Notes:
existsByIdbefore inserting still races when two requests arrive together. The(user_id, course_id)primary key is the last line of defence: catchDataIntegrityViolationException(orEntityExistsException) and return 409.existsByIdAndChapterCourseIdis a derived query that walkslesson.chapter.course.id, which is exactly the check the composite FK can’t do (the last pitfall in section 1.3).completeLessondoesn’t callsavefor an existingprogress: the entity is managed, so dirty checking writes it (see part 4).
What a senior would add:
- Move
user_course.statustoDONEonce the number ofDONElessons equals the course’s lesson count (aCOUNTquery or a stored counter updated atomically). - Add a
(course_id)index onuser_coursefor “learners of a course”. - Write integration tests against MySQL with Testcontainers, because H2 doesn’t catch every difference in
enumtypes and keywords.
Remember
- Pick the mapping for each relationship in the E-Learning schema and explain why User–Course doesn’t use
@ManyToMany. - Explain why
repository.save()with an@EmbeddedIdfires an extra SELECT, and three ways to avoid it. - Know what the composite FK to
user_courseblocks, what it doesn’t, and two ways to cover the gap. - Explain why returning entities from an API causes infinite recursion, leaks
passwordand triggers LAZY proxy errors. - Compare
@JsonIgnore,@JsonBackReference,@JsonIdentityInfoand DTOs.
Interview questions
Junior
Why shouldn’t you return JPA entities directly from an API?
Because entities expose every column, cause infinite recursion and uncontrolled queries, and tie the API to the schema; DTOs decouple the API contract from the storage model.
An entity maps the whole table, so it exposes password and internal fields too. Bidirectional relationships send Jackson into infinite recursion, LAZY associations cause LazyInitializationException or proxy serialization errors, and every association Jackson touches fires another query (N+1). Rename a column and clients break.
What’s wrong with naming a column order or a table user?
Both clash with SQL keywords: ORDER in every DBMS, USER in PostgreSQL and H2. Renaming (sort_order, users) is the cleanest fix.
An unquoted order column fails with a syntax error. A user table works on MySQL but breaks when you test with H2 or switch databases. Quoting works, but then every hand-written SQL statement must quote too.
Mid
Jackson reports infinite recursion when serializing an entity. Why, and how do you fix it?
A bidirectional relationship (User.fullName and FullName.user) makes Jackson go round in circles; the proper fix is mapping to DTOs in the service.
Newer Jackson stops at depth 1000 with a “nesting depth” error, older versions report Infinite recursion (StackOverflowError). Quick fixes: @JsonIgnore or @JsonBackReference on the reverse side, or @JsonIdentityInfo. With DTOs, entities need no Jackson annotations and there’s no cycle.
How do you map a many-to-many join table that has extra columns (rating, status)?
Turn the join table into its own entity with two @ManyToOnes, because @ManyToMany only manages the two FK columns.
The primary key can be an @EmbeddedId made of the two FKs, with @MapsId so the columns are both PK and FK; or an auto-increment id plus a unique constraint on the FK pair. Either way, the FK pair must be unique.
What is the No serializer found for class ...ByteBuddyInterceptor error when returning an entity?
Jackson is serializing an unloaded Hibernate LAZY proxy and trips over its internal hibernateLazyInitializer field.
If the transaction has already closed, it becomes LazyInitializationException. Don’t paper over it with @JsonIgnoreProperties or EAGER; fetch exactly what you need in the service (fetch join, @EntityGraph) and map to a DTO.
Senior
What’s unusual about saving an @EmbeddedId entity with repository.save()?
save() goes down the merge path and fires a SELECT before every INSERT, because a composite key is always assigned up front, so Spring Data thinks the entity already exists.
Spring Data decides between persist and merge from the id: a non-null id means “already exists”. Fix it with entityManager.persist, by implementing Persistable<ID> with your own isNew(), or by adding a @Version field (a null version means a new entity).
How would you constrain lesson progress so it can only be recorded for an enrolled course and a lesson that belongs to it?
A composite FK (user_id, course_id) to user_course guarantees the enrolment; “the lesson belongs to the course” must be checked in the service or enforced by denormalizing course_id into lesson.
A plain lesson_id FK can’t guarantee it, because lesson reaches course through chapter. Either check it with one exists query on lesson.chapter.course.id, or add lesson.course_id, UNIQUE(id, course_id) and a composite FK (lesson_id, course_id). The database option is airtight, but lesson.course_id must be kept in sync with the chapter.
Useful phrases for interviews
- “The enrolment table has its own columns, so I mapped it as an entity with an embedded id instead of a many-to-many.”
- “With @MapsId, the two foreign keys double as the composite primary key.”
- “
orderis a reserved word, so I renamed the column tosort_orderbefore it reached production.” - “The recursion only showed up during serialization, after the transaction had already committed.”
- “@JsonIgnore breaks the cycle, but it still leaks every other column, including the password hash.”
- “Controllers only ever see DTOs; the mapping happens in the service while the transaction is still open.”
- “The composite foreign key guarantees the enrolment exists, but not that the lesson belongs to that course, so the service checks that too.”
- “I’d rather have one account table with roles than three nearly identical user tables.”
Next up: ORM and JPA part 4: the persistence context, dirty checking and N+1.
Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.