By default, ColdFusion would use <bag> when you use type="array" to map "one-to-many" fieldtype.
/** Parent.cfc */
component persistent="true"
{
property name="id" fieldtype="id" generator="native";
property name="children" type="array" fieldtype="one-to-many" inverse="true" cfc="child" cascade="all";
}
Add this parent.hbxml below and save it in the same folder as parent.cfc if you want to use Indexed Collections. Hibernate will do all the bookkeeping behind the scene for you to preserve the order of the array by storing the order in the sortOrder column (int). Cool eh?
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class entity-name="parent" lazy="true" name="cfc:com.test.parent" table="parent">
<id name="id" type="int">
<column name="id"/>
<generator class="native"/>
</id>
<—- rename ‘bag’ to ‘list’ -->
<list name="children" cascade="all">
<key column="parent_id"/>
<—- set base="1" to match CF array index (optional, default to 0) -->
<list-index column="sortOrder" base="1"/>
<one-to-many class="cfc:com.test.child"/>
</list>
</class>
</hibernate-mapping>
Didn’t know it’s this easy! :)
Interesting. What's the difference between doing it this way and just adding orderby to the property?
ReplyDeleteproperty name="children" type="array" fieldtype="one-to-many" inverse="true" cfc="child" cascade="all" orderby="sortColumn;
Doing it your way means you need an additional sortColumn property of ormtype int, and you need to assign the value of sortColumn yourself.
ReplyDeleteIndexed Collections assigns the sortColumn value according to the array's index for you behind the scene.