Tuesday, April 5, 2011

org.hibernate.LazyInitializationException: failed to lazily initialize a collection


org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: acme.domain.model.Bla.mumbles, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:163)




Entity Bla contains a collection of Mumbles. The OneToMany annotation by default uses a LAZY loading approach.

If in your client layer you try to do a bla.getMumbles(), you get the exception LazyInitializationException. The session was closed in the EJB, and in the client you have only a detached entity.
To avoid the problem, in the EJB do a

bla.getMumbles().size();

(bla.getMumbles() is not enough!)


This will explicitly load ALL mumbles and the client will be happy.

Monday, April 4, 2011

ROA: Resource Oriented Architecture

I am reading RESTful Web Services


I am not in love with the book as I find it really verbose, it doesn't really catch my attention.

Anyway at page 216 they refer to ROA. The wikipedia article is very clarifying, the guidelines express the essence of the REST approach.
- stick all what you can in a URI
- documents should contain links (URIs) to related documents
- everything should be stateless


They talk a lot about "REPRESENTATION".
The table "RESTful Web Service HTTP methods" clearly shows what GET PUT POST and DELETE are supposed to do.

Here http://www.infoq.com/articles/rest-introduction
a good introduction on REST.

As usual, I keep thinking that all these technologies are simply CRAP, and that CORBA 20 years ago was doing much better than this. If you find a technology good only because anybody can write a URL in a browser and get a result, and you want to base on that your enterprise architecture, then good luck.

Friday, April 1, 2011

To Merge or To Persist....

http://download.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#merge%28T%29

Merge the state of the given entity into the current persistence context.


more info here (from the JPA 1.0 specs)

Hibernate has this to say.


if you entityManager.persist(anEntity), and they you entityManager.persist(anEntity) again, you will get a UNIQUE_KEY contraint violation (it will save it twice with the same ID)



in doubt, just use merge and you will be safe:
if you invoke it with a unpersisted entity it will do an INSERT
if you invoke it with an already persisted entity it will do an UPDATE