I've started using the object-relational mapper Hibernate recently. After studying the book "Introduction to Hibernate" by Minter/Linwood for a couple of days (not the most entertaining and inspring programming book I've read...) and trying examples, I felt ready to put my new knowledge to use. My first project was to convert an existing web application from using my own custom/proprietary O/R mapping to Hibernate, so it could be extended more easily and to be able to use one of the ready-made caches that come with Hibernate. It worked out well - even though creating the mappings caused me some headaches at times - and once you know Hibernate you absolutely don't wanna go back to the "manual" way.
Hibernate and auto-generated timestamps
Then I started a fresh project, with a clean database. Just like in the previous project, I needed to have timestamps for "created" and "last updated" on my objects. In the old project, the database was already set up with on update CURRENT_TIMESTAMP, which makes the database update the timestamp automatically when the row is updated. But since it wasn't obvious how Hibernate would set this up in the database from the definition in the mapping and since I wasn't really crazy about database magic and depending on specific database features, I was looking for other solutions. I read about Hibernate's <timestamp> and <version> features, which looked like they did just what I needed, and also help improve locking.
It seemed like a piece of cake to use Hibernate to generate the timestamps with the <timestamp> element inside the <class> of the mapping document. I changed the existing "updated"-<property> to a <timestamp>, but surprisingly that made the XML unparsable. The editor in Eclipse already complained with the red cross next to the class element and when running on the server I got an InvalidMappingException: Could not parse mapping document from resource...). It took me quite some time to find out what the problem was, but after taking a closer look at the DTD, I realized the order of the elements was important and wrong in my mapping. The <timestamp> element needs to be just after the <id> element. Once I changed that, the mapping could be parsed and Hibernate did it's job!
TrackBack URL: http://www.blogplanet.net/cgi-bin/copprhead/mt-tb.cgi/7