When I load an entity which contains lazy-loading fields and I want to send this entity through an object message with ActiveMQ, will I receive :
- The full entity (with lazy-loading fields loaded)
OR - The entity as sent (without lazy-loading fields loaded) ?
In any case do I need to put the Serializable marker in my entity ?
In case of answer 1 what do I need to do to get the entity as described in answer 2 ?
Lets assume you have an entity with some lazy loading fields like this:
When you receive this entity from your database only the
idfield will be loaded as thebarsfield is lazy loaded (OneToManyis lazy by default). Now when you pass this entity through JMS for example thebarsfield is not initialized because thegetBars()method isn’t called. When the remote end calls the getter it will get aLazyInitializationExceptionas the entity is detached and the collection isn’t initialized.If you however want the remote end to be able to call the
getBars()method you need to initialize the collection in some way. You can make the fetching of the collection eager using@OneToMany(fetch = FetchType.EAGER). An alternative is to use a separate query for eager loading the entity (which is my personal preference).Example:
If you really want to go wild and want the collection to be initialized lazily on the remote end you can take a look at Hibernate remote lazy loading using RMI. I’m not going to explain this because it seems out of the scope of the question. 😉