4. Advanced JPA & Database

0.0(0)
studied byStudied by 0 people
GameKnowt Play
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/29

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

30 Terms

1
New cards

What are the advantages of using Native Query in JPA?

Ưu điểm của việc dùng Native Query trong JPA là gì?


Allows writing pure SQL queries, fully utilizing the database capabilities.

  • Supports complex queries that JPQL cannot handle or is difficult to express.

  • Can improve performance in some cases by manually optimizing SQL.

  • Enables access to database-specific features (vendor-specific functions).

    Cho phép viết các câu truy vấn SQL thuần túy, tận dụng tối đa khả năng của cơ sở dữ liệu.

  • Hỗ trợ các câu truy vấn phức tạp mà JPQL không thể hoặc khó thực hiện được.

  • Tăng hiệu suất trong một số trường hợp tối ưu SQL thủ công.

  • Có thể truy cập các chức năng đặc thù của cơ sở dữ liệu (tính năng riêng của nhà cung cấp DB).

2
New cards

What are the disadvantages of using Native Query in JPA?

Nhược điểm của việc dùng Native Query trong JPA là gì?

  • Loses database independence, easily bound to a specific database type.

  • Harder to maintain and read compared to JPQL due to lack of strong typing support.

  • Does not leverage automatic entity mapping and ORM features.

  • Easy to cause errors if not careful in result handling (manual mapping needed).

    Mất tính độc lập với cơ sở dữ liệu, dễ bị ràng buộc vào loại DB cụ thể.

  • Khó bảo trì và đọc hơn so với JPQL vì không có sự hỗ trợ kiểu dữ liệu mạnh mẽ của JPA.

  • Không tận dụng được lợi ích của entity mapping tự động và các tính năng ORM.

  • Dễ gây lỗi nếu không cẩn thận trong việc xử lý kết quả trả về (phải mapping thủ công).

3
New cards

When should you prefer Native Query over JPQL in JPA?



When you need complex or highly optimized SQL queries that JPQL cannot support.

  • When you want to use special database features or syntax specific to the DB vendor.

  • When performance is critical and you need precise control over the SQL query.



Khi cần câu truy vấn SQL phức tạp hoặc tối ưu đặc thù mà JPQL không hỗ trợ.

  • Khi muốn tận dụng tính năng hoặc cú pháp đặc biệt của cơ sở dữ liệu cụ thể.

  • Khi hiệu năng là ưu tiên và cần kiểm soát chính xác câu truy vấn SQL.

4
New cards

Cách tối ưu query JPQL (How to optimize JPQL queries)

  • Chỉ select các trường cần thiết (Use SELECT new or specify fields, tránh SELECT *).

  • Dùng join fetch để giảm số lần truy vấn (n+1 problem).

  • Sử dụng paging (setFirstResult, setMaxResults) khi cần truy vấn lớn.

  • Tránh load quá nhiều dữ liệu không cần thiết.

  • Tận dụng caching của JPA khi có thể.

    Select only necessary fields (use SELECT new or specify fields, avoid SELECT *). Use join fetch to reduce queries (n+1 problem). Use paging (setFirstResult, setMaxResults) for large data. Avoid loading unnecessary data. Utilize JPA caching when possible.

5
New cards

ách tối ưu query Native Query (How to optimize Native queries)

  • Viết câu lệnh SQL rõ ràng, dùng chỉ mục (index) phù hợp.

  • Tránh SELECT *, chỉ lấy trường cần thiết.

  • Sử dụng explain plan của DB để kiểm tra hiệu năng.

  • Tối ưu joins, subqueries, và hạn chế truy vấn lặp.

  • Nếu nhiều Native Query giống nhau, cân nhắc tạo view hoặc stored procedure.

    Write clear SQL statements, use proper indexes. Avoid SELECT *, fetch only required fields. Use DB explain plan to check performance. Optimize joins, subqueries, and reduce repeated queries. For many similar native queries, consider views or stored procedures.

6
New cards

What are the differences between JPA and Hibernate?

Sự khác biệt giữa JPA và Hibernate là gì?

  • JPA is a specification; Hibernate is an implementation.

  • JPA defines interfaces and standard annotations, Hibernate provides the actual ORM implementation.

  • Hibernate offers extra features beyond JPA.

    JPA là chuẩn (specification), Hibernate là một implementation.

  • JPA định nghĩa interface và annotation chuẩn, Hibernate cung cấp ORM thực thi.

  • Hibernate có nhiều tính năng mở rộng ngoài chuẩn JPA.

7
New cards

How does Spring Boot simplify the configuration of JPA and database connections?

Spring Boot giúp đơn giản hóa cấu hình JPA và kết nối database như thế nào?

  • Tự động cấu hình thông qua starter spring-boot-starter-data-jpa.

  • Tự động cấu hình DataSource, EntityManagerFactory, TransactionManager dựa trên cấu hình trong file properties.

  • Giảm thiểu boilerplate cấu hình XML hoặc code thủ công.

    Auto-configuration via spring-boot-starter-data-jpa.

  • Automatically configures DataSource, EntityManagerFactory, TransactionManager based on properties.

  • Reduces XML/config boilerplate.

8
New cards

Explain the concept of Entity Lifecycle states in JPA.

Giải thích các trạng thái vòng đời của Entity trong JPA.

9
New cards

How to handle transactions in Spring Boot with JPA? What propagation behaviors exist?

Làm thế nào để xử lý transaction trong Spring Boot với JPA? Các loại propagation nào tồn tại?

  • Use @Transactional annotation at service or repository level.

  • Propagation types: REQUIRED (default), REQUIRES_NEW, SUPPORTS, MANDATORY, NEVER, NOT_SUPPORTED, NESTED.

  • Controls how transactions behave in nested or existing transactions.

    Sử dụng annotation @Transactional ở service hoặc repository.

  • Các kiểu propagation: REQUIRED (mặc định), REQUIRES_NEW, SUPPORTS, MANDATORY, NEVER, NOT_SUPPORTED, NESTED.

  • Kiểm soát cách transaction xử lý trong trường hợp transaction lồng nhau hoặc có transaction hiện tại.

10
New cards

What are the differences between FetchType.EAGER and FetchType.LAZY? When to use each?

Sự khác biệt giữa FetchType.EAGER và FetchType.LAZY là gì? Khi nào dùng?

  • EAGER: Data liên quan được load ngay khi entity được truy vấn.

  • LAZY: Data liên quan chỉ load khi truy cập đến, tránh tải dư thừa.

  • Use LAZY for performance; EAGER only when chắc chắn cần dữ liệu ngay.

    EAGER: Dữ liệu liên quan được load ngay khi truy vấn entity.

  • LAZY: Dữ liệu liên quan chỉ load khi thực sự truy cập (lazy loading).

  • Nên dùng LAZY để tối ưu hiệu năng, dùng EAGER khi chắc chắn cần dữ liệu ngay lập tức.

11
New cards

What is the N+1 select problem? How can it be solved in JPA?

  • N+1 problem: Khi truy vấn một list entity (1 query), và mỗi entity lại trigger 1 query con để lấy dữ liệu liên quan.

  • Giải pháp: Dùng JOIN FETCH trong JPQL, Entity Graph, hoặc Batch Fetching.

12
New cards

How to write a custom query in Spring Data JPA? What are the differences between method names, @Query JPQL, and native query?

  • Method names: Query tự động sinh theo tên method (e.g. findByName).

  • @Query: Tự viết JPQL hoặc SQL để tùy chỉnh.

  • Native Query: @Query(nativeQuery=true) viết SQL thuần.

13
New cards

What is the difference between save(), saveAndFlush(), and persist() in Spring Data JPA?

Sự khác biệt giữa save(), saveAndFlush(), và persist() trong Spring Data JPA?

  • save(): Lưu entity, đẩy xuống DB khi transaction commit.

  • saveAndFlush(): Lưu và flush ngay xuống DB, thực thi SQL ngay.

  • persist(): Phương thức của EntityManager, tương tự save() nhưng không trả entity.

14
New cards

How does optimistic locking work in JPA? What annotation is used?

Cách hoạt động của optimistic locking trong JPA? Dùng annotation nào?

  • Optimistic Locking dựa vào phiên bản (version) để tránh ghi đè dữ liệu khi nhiều transaction cùng cập nhật.

  • Dùng annotation @Version trên field version.

  • Khi commit, JPA kiểm tra version nếu khác sẽ ném OptimisticLockException.

    Dùng phiên bản (@Version) để phát hiện xung đột cập nhật dữ liệu khi nhiều transaction.

  • Nếu version không khớp khi commit, sẽ ném OptimisticLockException.

15
New cards

How can you improve the performance of large batch inserts or updates in JPA?

  • Tắt auto-flush và auto-commit tạm thời.

  • Sử dụng batching (spring.jpa.properties.hibernate.jdbc.batch_size).

  • Sau mỗi batch, gọi flush()clear() EntityManager để giải phóng bộ nhớ.

16
New cards

Why create indexes on query columns?

Tại sao phải tạo index trên cột truy vấn?

Helps the database search faster, improving query speed for large datasets.

Giúp database tìm kiếm nhanh hơn, cải thiện tốc độ truy vấn khi dữ liệu lớn.

17
New cards

Caching trong JPA gồm những cấp độ nào?

What are the cache levels in JPA?

First-level cache (in session), Second-level cache (shared across sessions), Query cache (cache query results).

First-level cache (trong session), Second-level cache (chia sẻ giữa các session), Query cache (cache kết quả truy vấn).

18
New cards

Batch processing giúp ích gì?

What is the benefit of batch processing?

Giảm số lần gọi database khi insert/update nhiều bản ghi, tăng hiệu suất.

Reduces number of database calls when inserting/updating many records, improving performance.

19
New cards

When should you avoid using JOIN FETCH?

Khi nào không nên dùng JOIN FETCH?

Khi join nhiều quan hệ OneToMany phức tạp vì có thể gây dữ liệu lặp và truy vấn chậm.

When joining multiple complex OneToMany relationships because it may cause data duplication and slow queries.

20
New cards

Làm sao theo dõi và tối ưu query JPA?

How to monitor and optimize JPA queries?

Dùng công cụ profiling như Hibernate statistics, p6spy, APM để giám sát và phân tích hiệu năng.

Use profiling tools like Hibernate statistics, p6spy, APM to monitor and analyze performance.

21
New cards

What are the main advantages of indexing in databases?

  • Significantly speeds up data retrieval (SELECT queries).

  • Enables faster searching, filtering, and sorting.

  • Improves performance of JOIN operations and WHERE conditions.

    Tăng tốc độ truy vấn dữ liệu (SELECT) rất nhiều.

  • Giúp tìm kiếm, lọc, sắp xếp dữ liệu nhanh hơn.

  • Hỗ trợ cho các phép join và các điều kiện WHERE hiệu quả hơn.

22
New cards

What are the disadvantages of indexing?

  • Consumes additional disk space.

  • Slows down write operations (INSERT, UPDATE, DELETE) because indexes need updating.

  • Poorly chosen indexes may not improve performance and cause overhead.

    Tốn thêm dung lượng lưu trữ trên đĩa.

  • Làm chậm thao tác ghi (INSERT, UPDATE, DELETE) vì phải cập nhật index.

  • Nếu đánh index không hợp lý, có thể không cải thiện được hiệu năng mà còn gây overhead.

23
New cards

What is the difference between @OneToMany and @ManyToOne in JPA? How does the owning side work?

Sự khác biệt giữa @OneToMany@ManyToOne trong JPA? Phía nào là owning side?

@ManyToOne is the owning side that contains the foreign key.
@OneToMany is the inverse side mappedBy the owning side.
Only the owning side controls updates to the relationship in the DB.

@ManyToOne là owning side giữ khóa ngoại.

  • @OneToMany là inverse side, dùng mappedBy trỏ tới owning side.

  • Chỉ owning side quyết định cập nhật quan hệ trong DB.

24
New cards

How to prevent SQL injection attacks in Spring Data JPA?

Làm sao ngăn chặn tấn công SQL injection trong Spring Data JPA?

  • Use parameter binding (@Param) instead of string concatenation.

  • Avoid dynamic query construction with raw strings.

  • Use JPQL or Criteria API with parameters.

    Dùng parameter binding (@Param), tránh nối chuỗi query.

  • Không dùng dynamic query bằng string thủ công.

  • Dùng JPQL hoặc Criteria API với tham số.

25
New cards

What is the difference between CascadeType.ALL and specifying cascade types individually?

Sự khác nhau giữa CascadeType.ALL và khai báo từng kiểu cascade riêng biệt?

  • CascadeType.ALL includes all cascade operations: PERSIST, MERGE, REMOVE, REFRESH, DETACH.

  • Specifying individually lets you control exactly which cascade types to apply.

    CascadeType.ALL bao gồm tất cả thao tác cascade: PERSIST, MERGE, REMOVE, REFRESH, DETACH.

  • Khai báo riêng giúp bạn kiểm soát chính xác các loại cascade áp dụng.

26
New cards

How to handle pagination with Spring Data JPA?

Làm sao xử lý phân trang với Spring Data JPA?

  • Use Pageable parameter in repository methods.

  • Return type can be Page<T> or Slice<T>.

  • Supports sorting and paging automatically.

    Dùng tham số Pageable trong method repository.

  • Kiểu trả về là Page<T> hoặc Slice<T>.

  • Hỗ trợ tự động phân trang và sắp xếp.

27
New cards

Explain how optimistic locking with @Version works in concurrent update scenarios.

Giải thích cách hoạt động của optimistic locking với @Version trong trường hợp cập nhật đồng thời.

  • Khi đọc entity, version được lưu.

  • Khi update, JPA kiểm tra version trong DB trùng với version lưu.

  • Nếu khác, throw OptimisticLockException để tránh ghi đè dữ liệu.

    Khi đọc entity, version được lưu lại.

  • Khi update, JPA kiểm tra version DB có trùng không.

  • Nếu không trùng, ném lỗi OptimisticLockException để tránh ghi đè.

28
New cards

Sự khác nhau cơ bản giữa CrudRepository và JpaRepository?

CrudRepository chỉ cung cấp CRUD cơ bản, còn JpaRepository mở rộng thêm chức năng như pagination, sorting và batch operations.

29
New cards

JpaRepository có thêm những phương thức nào mà CrudRepository không có?

Ví dụ: findAll(Pageable pageable), findAll(Sort sort), saveAll(Iterable<S> entities).

30
New cards

What is LazyInitializationException?

LazyInitializationException là gì?