SteelReed

Search

Search posts, questions…

4. Database & SQL

ORM and JPA: mapping the E-Learning schema, DTOs and JSON recursion

Building an E-Learning schema (user, full_name, course, chapter, lesson, user_course, user_course_lesson, address), mapping every relationship to JPA with @EmbeddedId and composite foreign keys, then fixing JSON recursion when returning bidirectional entities: @JsonIgnore, @JsonBackReference, @JsonIdentityInfo and DTOs.

17 Nov 20267 min readMid

–

1. The problem

GET /api/v1/users/{id} returns the User entity directly. Jackson walks User → fullName → user → fullName → ... until it throws Document nesting depth (1001) exceeds the maximum allowed, and the client gets a 500. After a @JsonIgnore fix, the response still contains the learner's hashed password.

2. Key idea

The E-Learning schema has 11 tables: user, teacher, the chain course → chapter → lesson, an enrolment table user_course with attributes, and a progress table user_course_lesson.

Relationship Mapping
User 1-1 FullName FullName holds FK user_id, unique = true; User has mappedBy = "user"
User n-n Address (pure) @ManyToMany + @JoinTable user_address, using a Set
Course → Chapter → Lesson @ManyToOne(fetch = LAZY, optional = false) on the child, no cascade REMOVE
User n-n Course (with rating, status) the UserCourse entity, @EmbeddedId + @MapsId
Per-lesson progress the UserCourseLesson entity: auto id, UNIQUE on the three columns, composite FK to user_course

@ManyToMany only manages two FK columns, so a join table with extra columns must be its own entity. Shared columns (created_date, updated_date) go in a @MappedSuperclass. ORDER is a keyword in every DBMS and USER is one in PostgreSQL and H2: rename to sort_order and users.

2.1 What goes out through the API?

Approach Use when Don't use when
DTO (record) mapped in the service the default it's never wrong
@JsonIgnore on the inverse side demos, a few-minute patch real APIs: still leaks sensitive fields, locks the response shape to the entity
@JsonManagedReference / @JsonBackReference avoid same drawbacks, harder to read
Spring Data projection interfaces reading a few columns complex mapping logic

Map to DTOs in the service while the transaction is open, so LAZY relationships can be read without open-in-view.

3. In Java

An n-n with attributes: the composite key is also the two FKs.

JAVA
@Embeddable
public record UserCourseId(Long userId, Long courseId) implements Serializable {}
 
@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;
    @Enumerated(EnumType.STRING) private EnrollmentStatus status;
}
 
public record UserResponse(Long id, String username, String fullName) {}   // no password
// service: return new UserResponse(u.getId(), u.getUsername(), u.getFullName().display());

Records can be @Embeddable since Hibernate 6.2. Other languages: TypeORM and Prisma (Node.js) also advise against returning entities from APIs.

Two key choices and an FK constraint that can't catch everything
@EmbeddedId + @MapsId (UserCourse) Auto id + UNIQUE (UserCourseLesson)
Gain matches the schema, lookup by primary key simpler entity, other tables reference it with one column
Cost an id class with equals/hashCode; save() goes through merge, one extra SELECT one more column and index

Either way, a unique constraint on the FK pair is mandatory.

The composite FK (user_id, course_id) from user_course_lesson to user_course blocks progress for courses the user isn't enrolled in, but doesn't guarantee the lesson belongs to that course: lesson_id only points at lesson. Check in the service with an exists query before writing, or denormalise a course_id into lesson so the DB can enforce it.

4. Working with AI

Hand to AI: generating entities from DDL, generating DTOs and mappers, tests that serialise responses.

Check in AI-written code:

  • Controllers don't return entities; responses are DTOs without password, tokens or internal fields.
  • Join tables with extra columns are their own entity, not @ManyToMany.
  • Ids are Long; @ManyToOne relationships are LAZY.
  • Enums are stored with EnumType.STRING; no column named order, no table named user.
  • Join tables have a unique constraint on the FK pair.

5. Exercises

Exercise 1: Review a JSON-loop fix

The AI fixed the nesting depth error with @JsonIgnore on FullName.user, saying "fixed, response OK". Do you approve? Name a test that proves what's still wrong.

Solution to Exercise 1

No. @JsonIgnore breaks the loop, but the entity still goes out whole: password, internal status, and every field added later leak. The response shape is tied to the entity, so changing a column changes the API.

Test: call GET /api/v1/users/1 through MockMvc and assert the JSON has no password key. It fails with the AI's fix.

Fix: record UserResponse(Long id, String username, String fullName), mapped in the service while the transaction is open. Drop the @JsonIgnore, since the entity no longer reaches Jackson.

Exercise 2: Choose a mapping for enrolments

user_course has user_id, course_id, rating, review, status. The AI suggests a @ManyToMany Set<Course> courses on User "to keep it simple". Decide, explain, and say when @ManyToMany is right.

Solution to Exercise 2

Not @ManyToMany: it only manages the two FK columns and can't read or write rating, review, status. Map it as a UserCourse entity with @EmbeddedId + @MapsId (section 3), or an auto id plus UNIQUE(user_id, course_id) if other tables need to reference it.

@ManyToMany is right for pure join tables with only two FK columns, like user_address. If extra columns might come later, make it an entity from the start: changing later is a big refactor.

Summary

  • The owning side holds the FK; 1-1 adds unique = true.
  • An n-n with attributes is its own entity with @EmbeddedId + @MapsId.
  • A unique constraint on the FK pair is mandatory.
  • Avoid names like order and user; store enums as strings.
  • Never return entities from the API; map to DTOs in the service.

Read more: Part 4: Persistence context and N+1.

Next up: ORM and JPA part 4: the persistence context, dirty checking and N+1.

Practice interview questions on this topic

All JPA & Hibernate questions →

Loading comments…