Thursday, October 30, 2008

Persisting A List of Custom Objects Using Hibernate in a Spring Env.

The prospect of persisting an object using hibernate into a database and then reading it back did not seem challenging with good old hibernate taking care of most things. 

Piece of cake? Not quite actually as I discovered while trying to do it for a List of custom objects. Let us see what were the challenges and how I found the solutions. Let us assume I wish to persist an object that contains the current situation of all stocks trading in the market. Our simplistic object has an id and a list of stocks: 


The list of stocks is made of a custom object:


And since we refuse to live without spring, we need some bean config:


With spring so near how can we forget maven and the pom dependencies:


Phew! Sometimes I forget how much these XML config make our lives easier (?).  Now, had it been my own custom object, I would have used @Embedded. But what do I do with a java collection. I was tempted to mark it with @Lob and it compiled fine. But when I actually tried to persist it, it gave me one big, fat ClassCastException: java.util.ArrayList cannot be cast to java.sql.Blob. OK, so objects don't turn into byte arrays overnight and that attempt was dumb and desperate. 

Then what? Referring "Java Persistence with Hibernate" (Bauer and King,2006) and official hibernate docs helped my to make my classes look like this:



Now this works like a charm: at least the part about starting your app, seeing your tables created perfectly and storing your objects at the right place with some class like:


In our next post we will see how we read this information back and use it if I face any difficulty with it as well!

No comments: