OK. I am trying to provide some sorting for collections which result from many-to-many relationships. I have seen previous posts which suggest that the DB "order-by" attribute of a collection mapping does not apply to objects in the "child" half of a M2M relationship, and that this behaviour is "not supported" (this is a little irritating actually). So, as a second choice, I have opted for in-memory sorting by ensuring all my persistent objects are Comparable. Initially I was using the "bag" collection type, simply because I am used to refering to Lists, but the list mapping requires an index column with "sequential integers numbered from zero", which I don't have (who does btw?).
So.. I have ended up using a Set as the type for all my collections. Now... I don't really want to change all of my persistent classes so that they identify collections as Sets (they currently identify them as simple Collections), but when I try to save an object in a Hibernate session, I get the following error:
Code:
java.lang.ClassCastException
at net.sf.hibernate.type.SortedSetType.wrap(SortedSetType.java:31)
at net.sf.hibernate.impl.WrapVisitor.processArrayOrNewCollection(WrapVisitor.java:78)
at net.sf.hibernate.impl.WrapVisitor.processCollection(WrapVisitor.java:49)
at net.sf.hibernate.impl.AbstractVisitor.processValue(AbstractVisitor.java:69)
at net.sf.hibernate.impl.WrapVisitor.processValues(WrapVisitor.java:93)
at net.sf.hibernate.impl.SessionImpl.flushEntity(SessionImpl.java:2488)
at net.sf.hibernate.impl.SessionImpl.flushEntities(SessionImpl.java:2454)
at net.sf.hibernate.impl.SessionImpl.flushEverything(SessionImpl.java:2256)
at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2235)
Now, SortedSetType.java:31 looks like this:
Code:
return new SortedSet( session, (java.util.SortedSet) collection );
Surely Hibernate does not expect me to actually use a SortedSet all the way up in my application?? The documentation states:
"Java type of a property holding a collection must be the interface type (ie. Map, Set or List; never HashMap, TreeSet or ArrayList)."
So.. I reluctantly changed all my Collection references to Set references, but because the runtime type of the Set is NOT a SortedSet, I still get this error.
I
must be doing something wrong here.. I cannot accept that Hibernate is forcing me to implement Collections with specific Java types!
Not very OO, or very AO for that matter.
Please help!
P.S I am using Hibernate 2.1.4 with MS SQL Server 2000. An example set mapping is below
Code:
<set name="groups" table="PersonGroup" lazy="false" sort="natural">
<key column="personId"/>
<many-to-many column="groupId" class="Group"/>
</set>