Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a list in hibernate by ordering instead of an index-field

This works:

<hibernate-mapping>
    <class name="Train" table="Trains">

        <id column="id" name="id" type="java.lang.String" length="4">
            <generator class="assigned" />
        </id>
        <set name="trips" cascade="all">
            <key column="trainId"/>
            <one-to-many class="Trip"/>
        </set>

    </class>
</hibernate-mapping>

But my trips are all naturally ordered by their scheduledDate. I would like to replace the Set with a List. Changing the collection to:

        <list name="trips" cascade="all" order-by="scheduledDate">
            <key column="trainId"/>
            <one-to-many class="Trip"/>
        </list>

does not work, since it now requires an <index/>. I don't want to add an index to my table, because the ordering is given by the date.

Any way this can be done? Or should I just get the Set from Hibernate, and then sort it myself in code? Seems unnecessary when we already have it ordered by the DB.

like image 284
Magnar Avatar asked Sep 15 '09 08:09

Magnar


1 Answers

Actually, this can be done with <bag>, <set> or <map> mappings. <bag> uses java.util.List semantics but does not maintain element indexes. By specifying it's order-by attribute, its elements will be ordered as part of SELECT:

<bag name="trips" cascade="all" order-by="scheduledDate">
    <key column="trainId"/>
    <one-to-many class="Trip"/>
</bag>

Note that order-by attribute needs to specify column name(s), not property name. The above can be mapped to java.util.List, you can do the same with java.util.Set by using <set> mapping. No need for comparators :-)

Details are here

like image 179
ChssPly76 Avatar answered Oct 07 '22 21:10

ChssPly76