Home > Java > javaTutorial > Should I Use Hibernate\'s Open Session in View Strategy?

Should I Use Hibernate\'s Open Session in View Strategy?

Linda Hamilton
Release: 2024-12-29 04:44:10
Original
171 people have browsed it

Should I Use Hibernate's Open Session in View Strategy?

Drawbacks of Hibernate Open Session in View Practice

Overview

Hibernate's Open Session in View (OSIV) strategy comes with several disadvantages, especially in multi-JVM environments and when immediate transaction commits are desired. Despite the convenience it offers in single-JVM applications, experts advise against its use.

Issues with OSIV

OSIV's primary concern stems from its unorthodox approach to data retrieval. It keeps the Persistence Context open during UI rendering, allowing lazy associations to be initialized upon demand. This leads to multiple drawbacks:

  • Auto-commit on Render: After service layer transactions complete, any subsequent statements triggered by UI rendering are executed in auto-commit mode, placing unnecessary load on the database server.
  • Blurred Concerns: The separation of concerns between service and UI layers becomes blurred, making testing and isolation more difficult.
  • Potential for N 1 Queries: UI layer limitations can lead to N 1 query problems, compromising performance.
  • Connection Lease Issues: OSIV holds the database connection throughout UI rendering, limiting transaction throughput and potentially causing pool congestion.

Avoiding LazyLoadExceptions

Instead of relying on OSIV, alternative strategies can be employed to prevent LazyLoadExceptions:

  • Fetching Associations: Explicitly initialize associations during service method calls.
  • Read-only Fetch: Mark association lists as read-only to prevent unexpected proxies.
  • Batch Fetching: Use @BatchSize and FetchMode.SUBSELECT to optimize fetches.
  • Data Access Layer (DAL) Queries: Craft custom DAL queries that precisely define data retrieval requirements.

Disabling OSIV in Spring Boot

In Spring Boot, OSIV is enabled by default. To disable it, add the following line to the application.properties file:

spring.jpa.open-in-view=false
Copy after login

This disables OSIV, allowing developers to handle LazyLoadExceptions in a more appropriate manner.

The above is the detailed content of Should I Use Hibernate\'s Open Session in View Strategy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template