开发者

Detached object in hibernate

开发者 https://www.devze.com 2023-01-22 16:10 出处:网络
What is 开发者_如何学JAVAthe benefit of detached object? What value do they provide? Thanks.When you need to keep a object \"alive\" between distinct hibernate sessions. Example: in web applications,

What is 开发者_如何学JAVAthe benefit of detached object? What value do they provide? Thanks.


When you need to keep a object "alive" between distinct hibernate sessions. Example: in web applications, if you're using the session-per-request pattern, and you need to keep the same hibernate entity between many pages.

Please take a look at the Hibernate docs:

Chapter 10: Working with objects

Chapter 11: Transactions and Concurrency


Suppose you need to execute a long transaction(user input taking time ) as well as object to be used as a presentation layer element. Now your object needs to play a double role.

  1. As a detached object (To be used as a presentation layer object )
  2. Reattached object (To complete transaction)

How is that possible?

Break the transaction in two transactions. as soon as the inner transaction will complete Object will be detached and it can work in the presentation layer. As soon as presentation work finish It will enter into another transaction and will work as an attached object.

So this all is possible due to attached object.


When there are long transactions that need to be handled, then it is logical to break the long transaction up into two or more transactions. Detached objects can be used to carry the information up to UI layer and can be re-attached to a new transaction with help of another session.

On the other hand, it is not very advisable to use detached objects in such scenarios rather DTO's (Data Transfer Objects) can serve the purpose fairly well here.

0

精彩评论

暂无评论...
验证码 换一张
取 消