Đến nội dung chính
notes.vinhnq.com

Tìm kiếm

Database & ORMMid24 phút đọc

ORM và JPA: ánh xạ schema E-Learning, DTO và vòng lặp JSON

Ôn 17 thẻ
Trong bài này

Cụm bài ORM và JPA: 1. Entity và repository · 2. Quan hệ entity · 3. Schema E-Learning, DTO, JSON · 4. Persistence context và N+1 · 5. JPQL, @Transactional, locking

Bài 2 giải thích từng loại quan hệ trên mô hình rút gọn; bài này áp chúng vào schema thật của pet project E-Learning: mười một bảng, một quan hệ n-n có thuộc tính và một bảng tiến độ với khoá ghép. Nửa sau xử lý chuyện xảy ra ngay khi trả các entity đó ra API: Jackson lặp vô hạn, vì sao slide dùng @JsonIgnore, và vì sao cách đúng là DTO. Nên đọc trước bài 1 (entity, repository, các tầng) và bài 2 (owning side, mappedBy, cascade); mọi mapping trong bài đã chạy thử trên Hibernate 6.6 với H2.

1. Schema E-Learning của khoá và cách ánh xạ sang JPA

Ý chính: mỗi quan hệ trong schema có một mapping riêng: chuỗi 1-n dùng @ManyToOne ở bảng con, 1-1 đặt owning side ở bảng giữ FK, n-n thuần dùng @ManyToMany, còn n-n có thêm cột phải thành entity riêng.

Slide buổi ORM 2 đưa thiết kế đầy đủ của pet project E-Learning, và bài tập yêu cầu ánh xạ đúng thiết kế đó. (Phần truy vấn SQL trên cùng mô hình nằm ở bài tập SQL JOIN và GROUP BY.)

1.1. Các bảng và quan hệ

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
  }
Bảng Cột chính Vai trò
user id, username (unique), password, nickname, status Học viên
full_name id, first_name, mid_name, last_name, status, user_id FK Phía phụ thuộc của quan hệ 1-1 với user
admin, teacher id, username (unique), password, status Tài khoản quản trị và giảng viên, mỗi loại một bảng
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 n-n User–Course có thuộc tính (đánh giá, tiến độ khoá)
user_course_lesson user_id, course_id, lesson_id, status Tiến độ từng bài của một lượt đăng ký
user_address, address (user_id, address_id); country, city, district, street, address_detail n-n User–Address thuần

Mọi bảng (trừ hai bảng trung gian thuần) có thêm created_date, updated_date. Ba bộ giá trị cố định:

  • status của các bảng cấu hình (user, admin, teacher, course, chapter, lesson): ACTIVE / INACTIVE.
  • status của user_course và user_course_lesson: START (mặc định) / PROCESSING / DONE.
  • lesson.type: VIDEO / PDF / DOCX / SLIDE.

1.2. Chỗ cần sửa khi làm theo slide

  • Lỗi gõ trên sơ đồ: “Tearcher”/“tearcher_id” (đúng là teacher, teacher_id), “User_Course_Lession”, “Lession” (đúng là lesson), kiểu bài “SLICE” (đúng là SLIDE). Gõ y nguyên thì tên bảng, cột và hằng enum sai từ đầu; sửa về sau là một migration.
  • Hai tên đụng từ khoá SQL, xem khối dưới.

1.3. Ánh xạ từng bảng

Cột chung (created_date, updated_date) đặt trong một @MappedSuperclass (lớp cha chứa cột chung, bản thân không phải entity). Mỗi bộ giá trị cố định là một enum lưu dạng chuỗi (EnumType.STRING).

Quan hệ Mapping
User 1-1 FullName FullName giữ FK user_id (owning side, unique = true để DB chặn hai họ tên cho một user); User có mappedBy = "user", cascade = ALL, orphanRemoval
User n-n Address (thuần) @ManyToMany + @JoinTable user_address, dùng Set
Teacher → Course → Chapter → Lesson @ManyToOne(fetch = LAZY, optional = false) ở bảng con; bảng cha chỉ khai báo collection khi cần điều hướng, không cascade REMOVE
User n-n Course (có thuộc tính) Entity UserCourse, khoá ghép @EmbeddedId + @MapsId
Tiến độ từng bài Entity UserCourseLesson: id tự tăng, UNIQUE trên bộ ba cột, FK ghép sang user_course

So với code trên slide: slide dùng private int id và fetch = FetchType.EAGER ở phía User. Nên dùng Long (null nghĩa rõ ràng là “chưa lưu”) và để LAZY ở phía owning. Phía inverse của @OneToOne vẫn bị load ngay (xem khối cạm bẫy ở mục 1.4 của bài 2), nên nếu API hiếm khi cần họ tên thì có thể bỏ hẳn field fullName ở User.

Code đầy đủ: BaseEntity, enum, 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 }               // bảng cấu hình
public enum ProgressStatus { START, PROCESSING, DONE } // user_course, user_course_lesson
public enum LessonType { VIDEO, PDF, DOCX, SLIDE }

User, FullName (1-1) và Address (n-n thuần):

@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;            // chỉ lưu hash (BCrypt), không bao giờ trả ra API

    @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) {   // giữ hai chiều đồng bộ
        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<>();
}

Chuỗi 1-n Course và Lesson:

@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 (có @OneToMany(mappedBy = "teacher") List<Course> courses), Admin và Chapter (có sortOrder và @ManyToOne Course course) viết theo đúng khuôn trên.

User – Course (n-n có thuộc tính): user_course có rating, review, status, nên không dùng @ManyToMany được (nó chỉ quản lý hai cột FK). Ánh xạ thành entity UserCourse với khoá chính ghép @EmbeddedId, và @MapsId để hai cột của khoá cũng chính là hai FK (derived identity: id lấy từ quan hệ):

@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;
    }
}

Tiến độ từng bài (user_course_lesson): id tự tăng làm khoá chính, bộ ba cột của slide nằm trong một unique constraint. FK ghép (user_id, course_id) trỏ về user_course, nên DB chặn luôn việc ghi tiến độ cho khoá user chưa đăng ký.

Code UserCourseLesson và kết quả chạy thử trên 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; }
}

Mình chạy bộ mapping này trên Hibernate 6.6 với H2 (chế độ MySQL): tạo user kèm họ tên và địa chỉ, giảng viên, khoá học, chương, bài, một lượt đăng ký và một dòng tiến độ, rồi đọc lại bằng find(UserCourse.class, new UserCourseId(userId, courseId)).

Hibernate sinh đúng PK ghép cho user_course, FK ghép từ user_course_lesson sang user_course, UNIQUE cho full_name.user_id. Với EnumType.STRING nó tạo luôn cột kiểu enum('ACTIVE','INACTIVE').

Thêm hai lựa chọn thiết kế: bảng tài khoản và thứ tự cột của PK ghép

2. Trả entity ra JSON: vòng lặp vô hạn, @JsonIgnore và DTO

Ý chính: quan hệ hai chiều làm Jackson đi vòng mãi khi serialize (chuyển object thành JSON). @JsonIgnore chỉ cắt vòng; cách đúng là map entity sang DTO (object chỉ chở dữ liệu ra API) trong service, khi transaction còn mở.

2.1. Vấn đề: quan hệ hai chiều làm Jackson lặp mãi

Demo trên slide: GET /api/v1/users/{id} trả thẳng entity User, JSON có full_name lồng bên trong cùng danh sách addresses. Để chạy được, slide phải đặt @JsonIgnore lên FullName.user và Address.users. Lý do: Jackson đi qua mọi getter/field, nên với mapping hai chiều ở mục 1.3 nó đi User → fullName → user → fullName → ... không điểm dừng.

Chạy đúng tình huống đó (Hibernate 6.6, Jackson 2.18, entity chưa có @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"]->...)

Jackson cũ hơn không có giới hạn độ sâu này, nên lỗi hiện thành StackOverflowError, bọc trong JsonMappingException: Infinite recursion (StackOverflowError). Spring trả 500 cho client.

2.2. Cách của slide: @JsonIgnore ở phía tham chiếu ngược

@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<>();
}

Vòng lặp bị cắt: User có fullName, nhưng trong fullName không còn user. Đổi lại:

  • Một chiều mất vĩnh viễn trong JSON. GET /addresses/{id} không bao giờ trả được danh sách người ở, kể cả khi màn hình cần.
  • Mọi field còn lại đều ra API. Bản có @JsonIgnore trả {"id":1,"username":"johndoe","password":"$2a$10$hash","fullName":{"id":1,"lastName":"Doe"}}. Entity User và Teacher trên slide đều có cột password.

2.3. Các cách khác của Jackson

Cách Đặt ở đâu JSON của User (đã chạy thử) Ghi chú
@JsonIgnore Phía tham chiếu ngược {"id":1,...,"fullName":{"lastName":"Doe"}} Đơn giản; chiều ngược mất hẳn
@JsonManagedReference / @JsonBackReference @JsonManagedReference ở phía cha, @JsonBackReference ở phía con {"id":1,"fullName":{"lastName":"Doe"}} Như @JsonIgnore khi ghi, nhưng khi đọc JSON vào thì Jackson tự gán lại tham chiếu ngược
@JsonIdentityInfo Trên cả hai class {"id":1,"fullName":{"id":7,"lastName":"Doe","user":1}} Lần thứ hai gặp cùng object thì chỉ ghi id; client phải hiểu quy ước này
DTO (record) Lớp riêng cho response {"id":1,"username":"johndoe","fullName":{...},"cities":[...]} Kiểm soát hoàn toàn, không dính Hibernate

Một lỗi khác cùng gốc, hay gặp khi trả entity có quan hệ LAZY:

2.4. Cách nên dùng: map sang DTO trong 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"})   // lấy đủ trong một lần, tránh 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 khi transaction còn mở
                .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); }
}
  • Entity không cần annotation Jackson nào; DTO là cây không có vòng nên quan hệ hai chiều hết là vấn đề.
  • password không bao giờ rời khỏi service.
  • Muốn JSON snake_case như slide (full_name, address_detail): đặt spring.jackson.property-naming-strategy=SNAKE_CASE hoặc @JsonProperty trên từng field của DTO.
Nâng cấp lên Jackson 3 (Spring Boot 4)

Bài tập

Bài tập buổi ORM về quan hệ, trên pet project E-Learning (một bản khoá học khác dùng đề quản lý khách sạn với Hotel, Room, Employee; cách làm giống hệt). Đề đầy đủ ở bài Pet project thực hành; các bài tập tạo entity, repository và CRUD ở bài 1 của cụm.

Bài 4: Khai báo quan hệ cho các entity E-Learning và tiếp tục làm API

Yêu cầu (diễn đạt lại): bổ sung annotation quan hệ (1-1, 1-n, n-n) cho các entity sao cho khớp với khoá ngoại trong schema E-Learning, rồi tiếp tục hoàn thiện logic dữ liệu phía sau các API.

Lời giải Bài 4: mapping và ba API đăng ký, hoàn thành bài, xem user

Phần mapping: đúng như mục 1.3.

  • User 1-1 FullName: FullName giữ FK user_id (owning side, unique = true), User có mappedBy = "user" kèm cascade = ALL + orphanRemoval vì họ tên thuộc về user.
  • Teacher 1-n Course 1-n Chapter 1-n Lesson: @ManyToOne(fetch = LAZY, optional = false) ở phía con, không cascade REMOVE từ phía cha.
  • User n-n Address: @ManyToMany + @JoinTable user_address, kiểu Set.
  • User n-n Course có thuộc tính: entity UserCourse với @EmbeddedId + @MapsId.
  • Tiến độ: entity UserCourseLesson, FK ghép (user_id, course_id) sang user_course, unique trên bộ ba cột.

Phần API: ba thao tác chính: đăng ký khoá học, đánh dấu hoàn thành một bài, và xem thông tin user (mục 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, bỏ qua cho gọn

    @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);   // id gán sẵn: persist thay vì save() để khỏi 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);     // bài không thuộc khoá này
        }
        UserCourseLesson progress = progressRepository
                .findByUserCourseAndLessonId(enrollment, lessonId)
                .orElseGet(() -> progressRepository.save(
                        new UserCourseLesson(enrollment, lessonRepository.getReferenceById(lessonId))));
        progress.complete();                 // dirty checking sinh UPDATE khi 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);
}

Giải thích:

  • existsById trước khi insert vẫn có race condition khi hai request đến cùng lúc. Primary key (user_id, course_id) là tuyến phòng thủ cuối: bắt DataIntegrityViolationException (hoặc EntityExistsException) và trả 409.
  • existsByIdAndChapterCourseId là derived query đi qua lesson.chapter.course.id, chính là phần kiểm tra mà FK ghép không làm được (khối cạm bẫy cuối mục 1.3).
  • completeLesson không gọi save cho progress đã tồn tại: entity đang managed nên dirty checking tự ghi (xem bài 4).

Senior sẽ làm thêm:

  • Chuyển user_course.status sang DONE khi số bài DONE bằng tổng số bài của khoá (một câu COUNT hoặc cột đếm lưu sẵn, cập nhật nguyên tử).
  • Thêm index (course_id) cho user_course để tra “học viên của khoá”.
  • Viết test tích hợp với Testcontainers MySQL, vì H2 không bắt được mọi khác biệt về kiểu enum và từ khoá.

Ghi nhớ

  • Chọn được mapping cho từng quan hệ của schema E-Learning và giải thích vì sao User–Course không dùng @ManyToMany.
  • Giải thích được vì sao repository.save() với @EmbeddedId bắn thêm SELECT, và ba cách tránh.
  • Biết FK ghép sang user_course chặn được gì, không chặn được gì, và hai cách bù.
  • Giải thích được vì sao trả entity ra API gây lặp vô hạn, lộ password và lỗi proxy LAZY.
  • So sánh được @JsonIgnore, @JsonBackReference, @JsonIdentityInfo và DTO.

Câu hỏi phỏng vấn

Junior

Vì sao không nên trả entity JPA thẳng ra API?

Vì entity lộ mọi cột, gây lặp vô hạn và query ngoài kiểm soát, và buộc API vào schema; DTO tách hợp đồng API khỏi mô hình lưu trữ.

Entity ánh xạ toàn bộ bảng nên lộ cả password hay trường nội bộ. Quan hệ hai chiều làm Jackson lặp vô hạn, quan hệ LAZY gây LazyInitializationException hoặc lỗi serialize proxy, và Jackson chạm quan hệ nào là bắn thêm query (N+1). Đổi tên cột là vỡ client.

Đặt tên cột là order hoặc bảng là user có vấn đề gì?

Cả hai đụng từ khoá SQL: ORDER ở mọi DBMS, USER ở PostgreSQL và H2. Đổi tên (sort_order, users) là cách gọn nhất.

Cột order không quote sẽ lỗi cú pháp. Bảng user chạy trên MySQL nhưng hỏng khi test bằng H2 hay chuyển DB. Quote được, nhưng mọi SQL viết tay phải quote theo.

Mid

Jackson báo lặp vô hạn khi serialize entity. Vì sao và sửa thế nào?

Quan hệ hai chiều (User.fullName và FullName.user) khiến Jackson đi vòng mãi; sửa đúng là map sang DTO trong service.

Jackson mới dừng ở độ sâu 1000 với lỗi “nesting depth”, bản cũ báo Infinite recursion (StackOverflowError). Sửa tạm: @JsonIgnore hoặc @JsonBackReference ở phía ngược, hoặc @JsonIdentityInfo. Với DTO, entity không cần annotation Jackson và không có vòng.

Ánh xạ bảng trung gian n-n có thêm cột (rating, status) thế nào?

Biến bảng trung gian thành entity riêng với hai @ManyToOne, vì @ManyToMany chỉ quản lý hai cột FK.

Khoá chính có thể là @EmbeddedId gồm hai FK, dùng @MapsId để hai cột vừa là PK vừa là FK; hoặc id tự tăng kèm unique constraint trên cặp FK. Cách nào cũng phải có ràng buộc unique trên cặp FK.

Lỗi No serializer found for class ...ByteBuddyInterceptor khi trả entity là gì?

Jackson đang serialize một proxy LAZY chưa load của Hibernate và vấp vào field nội bộ hibernateLazyInitializer.

Nếu transaction đã đóng thì thành LazyInitializationException. Không nên che bằng @JsonIgnoreProperties hay EAGER; fetch đúng dữ liệu cần trong service (fetch join, @EntityGraph) rồi map sang DTO.

Senior

Entity có @EmbeddedId được lưu bằng repository.save() thì có gì bất thường?

save() đi đường merge và bắn một SELECT trước mỗi INSERT, vì khoá ghép luôn được gán sẵn nên Spring Data tưởng entity đã tồn tại.

Spring Data quyết định persist hay merge dựa vào id: id khác null nghĩa là “đã tồn tại”. Sửa bằng entityManager.persist, implement Persistable<ID> với isNew() tự quyết, hoặc thêm field @Version (version null nghĩa là entity mới).

Thiết kế ràng buộc sao cho tiến độ bài học chỉ được ghi cho khoá đã đăng ký và bài thuộc đúng khoá đó?

FK ghép (user_id, course_id) sang user_course đảm bảo đã đăng ký; còn “bài thuộc khoá” phải kiểm tra trong service hoặc phi chuẩn hoá course_id vào lesson.

FK đơn lesson_id không đảm bảo được vì lesson nối với course qua chapter. Hoặc kiểm tra bằng một query exists theo lesson.chapter.course.id, hoặc thêm lesson.course_id, UNIQUE(id, course_id) và FK ghép (lesson_id, course_id). Cách DB chắc chắn hơn nhưng phải giữ lesson.course_id đồng bộ với chương.

Từ vựng tiếng Anh

Term Phát âm Nghĩa Ví dụ câu dùng trong phỏng vấn
composite key /kəmˈpɑː.zɪt kiː/ khoá chính ghép nhiều cột “The enrolment table uses a composite key of user and course.”
embedded id /ɪmˈbed.ɪd aɪ diː/ class id nhúng cho khoá ghép “I map the composite key with an embedded id and two MapsId associations.”
derived identity /dɪˈraɪvd aɪˈden.tə.ti/ id lấy từ quan hệ (@MapsId) “With derived identity, the foreign keys double as the primary key.”
reserved word /rɪˈzɜːrvd wɜːrd/ từ khoá dành riêng của SQL “order is a reserved word, so I renamed the column to sort_order.”
serialization /ˌsɪr.i.ə.ləˈzeɪ.ʃən/ chuyển object thành JSON “The bug only showed up during serialization, after the transaction had committed.”
infinite recursion /ˈɪn.fə.nət rɪˈkɜːr.ʒən/ đệ quy vô hạn “A bidirectional mapping sent Jackson into infinite recursion.”
back reference /bæk ˈref.ər.əns/ tham chiếu ngược từ con về cha “The back reference is skipped on output and restored on input.”
DTO (data transfer object) /diː tiː oʊ/ object chở dữ liệu ra API “Controllers only ever see DTOs, never entities.”
mapped superclass /mæpt ˈsuː.pər.klæs/ lớp cha chứa cột chung, không phải entity “Audit columns live in a mapped superclass.”
leak /liːk/ để lộ dữ liệu “Returning the entity leaked the password hash.”

Tiếp theo: ORM và JPA bài 4: persistence context, dirty checking và N+1.


Ghi chép dựa trên khoá Fundamentals of Backend (Ronin Engineer), viết lại theo cách hiểu của mình.