Initializing Persisted Collections (JPA/Hibernate)

Here’s a good question/answer that I came across today over at Stackoverflow. The answer is that it NOT a good idea to set a collection inside of a getter or setter method because:

I would strongly discourage lazy initialization for properties in an ORM entity.

We had a serious issue when doing lazy initialization of an entity property using Hibernate, so I would strongly discourage it. The problem we saw was manifest by a save taking place when we were issuing a search request. This is because when the object was loaded the property was null, but when the getter was called it would return the lazy initialized object so hibernate (rightly) considered the object dirty and would save it before issuing the search.

I’ve been burned by this as well.

[Stackoverflow: Is it good practice to initialize fields inside a JPA entity getter?]

About these ads

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s