开发者

Recommendation for using equals in Entities and avoiding LazyInitializationExceptions?

In the beginning there is a problem that wants to be solved. In my case i got an LazyInitializationException while using indexof in a Collection to retrieve an Object for manipulation. Here i start to think about using equals in EntityBeans (OR-Mapper at all). I know there are some discussions about overriding equals in association with OR-Mapper as hibernate like

[1] Entities equals(), hashCode() and toString(). How to correctly implement them?

[2] To equals and hashcode or not on entity classes, that is the question.

[3] Overriding equals and hashCode 开发者_开发问答in Java

I currently have some entities which implements the equals but inside the code i could not use equals several times because of the LazyInitializationExceptions. So i had to workaround and use eg. the name property of the object to identify it's equality. From my point of view the whole 'LazyInitializationException-thing' is not really mentioned in this questions.

I'd like to know have you got some good patterns or real live recommendations how to avoid such exception in an equal-Method. Shall i use some helper Methodes to distinguish if a Object of a class is already initialized (4) or should i apdicate the use of equals and use helper classes instead (2)? And what is about catching LazyInitializationExceptions in the equals?


[Edit]: If you put equals in context with the initialization of the Object then it will gain importance. Sometimes it is nessesary to have the Object fully initialized but sometimes you don't want to. Because you just need the Object itself (name, id, ...) not its Collection-Properties. So just for equalization you have to reattach the Object and load the whole bunch you don't realy need? Are there any other solutions for such a problem?


LazyInitializationException and equals(), hashCode() et al have little to do with each other. You can a LazyInitializationException when a lazily loaded entity tried to access a related entity that has not yet been loaded, and and the entity has been disconnected or evicted from the Session.

There are two fixes for this:

  1. eagerly load the entity, and it's related entities, before closing the session.
  2. Use the "open session in view" pattern to keep the session open for the duration of the request.

Both of these approaches are discussed in the link below.

  • JavaLobby: Hibernate, Understanding Lazy Fetching
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜