This is a mirror of official site: http://jasper-net.blogspot.com/

Minimizing Hibernate Schema Complexity

| Friday, April 8, 2011
In my applications I persist a lot of structured data into the database. Hibernate and other ORMs are great at making this easy to do. One problem is that they tend to map the entire object structure to rigidly structured database fields and tables. Quite often that's just overkill.
STRINGS AS A BLACK BOX DATATYPE

Take strings for instance. A VARCHAR makes perfect sense if you know the string will always be less than, say, 30 characters. Even if your not going to use that string field in a where clause, ever.
But if you won't know the max size the string will be for every instance, or it could be a very large string and you're never going to use it in a search, then your fine using a LOB column to store that string.

Modern ORMs will even read/write the whole string value into/out from the LOB column for you. Or give you the CLOB instance itself for better performance, whichever you prefer.

I've experienced many DBAs that don't like the use of LOB columns. But I've never understood that, as this is exactly the purpose that LOB columns were meant to solve. The storage of arbitrary data in the database, no different than in a file, without any sort of internal random access, indexing, or searching. A Blackbox-column to the database server, if you will.

COMPLICATED OBJECT GRAPHS

Worse is when you have classes with lots of field and subobjects. This can get messy, even if they're just value objects.
The multiple tables, table hierarchies, link tables, and huge column lists that can result, while entirely valuable for some classes, are just overkill for others. Especially when you won't be indexing, searching or retrieving individually, any of those fields/rows/objects.

PERSISTING SERIALIZED CLASSES

ORMs can persist a whole instance into one field. They do so using serialization of some form or another to turn the instance into flat data like a byte array. Then this data can be persisted as a BLOB value.
In the case of Hibernate, its as simple as marking a reference (non primitive) field with @Lob, just as with the strings. But in this case, by default, Hibernate will use the standard java serialization mechanism. Which some would take exception *cough* to.

You can provide your own serialization mechanism of course. I'm not sure how to do this across the board for hibernate. But my solution is just to create a custom hibernate UserType implementation. Then I can mark the fields with this custom UserType, that I want stores as non-entities.

This is surprisingly easy.

XML

For the serialization format, I chose XML. There are a number of good XML serializers for java objects. Some even work well on arbitrary classes, though you shouldn't be putting just any classes in your databases columns.

Posted via email from Jasper-net

0 comments: