Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate empty collection in component

I have a component mapped using Hibernate. If all fields in the component in the database are null, the component itself is set to null by hibernate. This is the expected behavior and also what I need.

The problem I have, is that when I add a bag to that component, the bag is initialized to an empty list. This means the component has a non null value... resulting in the component being created.

Any idea how to fix this?

<class name="foo.bar.Entity" table="Entity">
<id name="id" column="id">
    <generator class="native" />
</id>

<property name="departure" column="departure_time" />
<property name="arrival" column="arrival_time" />

<component name="statistics">
    <bag name="linkStatistics" lazy="false" cascade="all" >
        <key column="entity_id" not-null="true" />
        <one-to-many class="foo.bar.LinkStatistics" />
    </bag>

    <property name="loggedTime" column="logged_time" />

    ...
</component>

A criteria with Restirctions.isNull("statistics") does return the expected values.

like image 695
Jurgen Hannaert Avatar asked May 07 '10 07:05

Jurgen Hannaert


1 Answers

The basic problem here is that Hibernate can't distinguish between null collections and empty collections, so it treats them both as empty: non-null.

I suggest you change your Statistics component to an real entity instead. Then your foo.bar.Entity class has a reference, which can be null. This is not ideal because you'll have to create another table to store the Statistics entity, but if you want the null vs empty semantic distinction, that's a way to get it.

like image 129
sharakan Avatar answered Nov 12 '22 12:11

sharakan