The Holy Java

Building the right thing, building it right, fast

Framework Joy: Load in Hibernate Updates Data

Posted by Jakub Holý on March 31, 2014

Would you ever guess that this line

// Load Buyer from DB by id using Spring's HibernateTemplate:
final Buyer traveller = (Buyer) hibernateTemplate.load(Buyer .class, new Long(id));

could lead to a constraint-validation exception during a batch update or delete and re-insert rows (loosing all columns Hibernate does not know about)? I was quite surprised.

In particular buyer’s bonusCards get deleted and re-inserted, because Hibernate believes that the collection of cards is dirty, even though it has just loaded it from the DB. I am not exactly sure why (preventing false positives in dirty checks requires some black magic), this is the configuration:

<class name="Buyer" ...>
    <set name="bonusCards " table="bonus_cards">
        <key column="buyer_id"/>
        <composite-element class="BonusCard">
            <property name="number" column="number" not-null="false"/>
            <property name="expiredate" column="expdate"/>

Of course Hibernate certainly has good reasons to update and delete+re-insert data upon load and we could certainly get rid of (some of) these updates by configuring Hibernate better. But it still demonstrates nicely the hidden cost of using a complex framework – in this case, it behaves quite unexpectedly and requires extensive knowledge to set up properly and to troubleshoot.

Sorry, the comment form is closed at this time.

%d bloggers like this: