I'm trying to maintain a sorted set of Subjects in a Study object. Subjects should be sorted by their name property. I have been using the order-by attribute and a LinkedHashSet, but this results in an improperly sorted set immediately after adding a new Subject.
I thought the proper workaround would have been to use the sort="natural" attribute, a SortedSet object, and implement Comparable on the Subject object, but I'm getting an NPE when I try that. The compareTo method reads:
Code:
public int compareTo(Object object) {
Subject subject = (Subject)object;
return getName().compareTo(subject.getName());
}
The relevant portion of the stack trace reads:
Code:
java.lang.NullPointerException
at com.rhoworld.edc.model.Subject.compareTo(Subject.java:66)
at java.util.TreeMap.compare(TreeMap.java:1081)
at java.util.TreeMap.put(TreeMap.java:459)
at java.util.TreeSet.add(TreeSet.java:205)
at java.util.AbstractCollection.addAll(AbstractCollection.java:315)
at java.util.TreeSet.addAll(TreeSet.java:251)
at net.sf.hibernate.collection.Set.endRead(Set.java:252)
at net.sf.hibernate.loader.Loader.doFind(Loader.java:200)
at net.sf.hibernate.loader.Loader.loadCollection(Loader.java:602)
at net.sf.hibernate.loader.OneToManyLoader.initialize(OneToManyLoader.java:102)
at net.sf.hibernate.impl.SessionImpl.initialize(SessionImpl.java:2897)
at net.sf.hibernate.collection.PersistentCollection.getInitialValue(PersistentCollection.java:128)
at net.sf.hibernate.type.PersistentCollectionType.getCollection(PersistentCollectionType.java:74)
at net.sf.hibernate.type.PersistentCollectionType.resolveIdentifier(PersistentCollectionType.java:177)
at net.sf.hibernate.impl.SessionImpl.initializeEntity(SessionImpl.java:1959)
at net.sf.hibernate.loader.Loader.doFind(Loader.java:196)
at net.sf.hibernate.loader.Loader.loadEntity(Loader.java:587)
at net.sf.hibernate.loader.EntityLoader.load(EntityLoader.java:42)
at net.sf.hibernate.persister.EntityPersister.load(EntityPersister.java:396)
at net.sf.hibernate.impl.SessionImpl.doLoad(SessionImpl.java:1889)
at net.sf.hibernate.impl.SessionImpl.doLoadByClass(SessionImpl.java:1757)
at net.sf.hibernate.impl.SessionImpl.load(SessionImpl.java:1688)
My theory is that the name property hasn't been loaded from the database yet, but hibernate is going ahead and stuffing the object into a collection (presumably the Study's since I'm not yet using lazy loading on these collections.)
Any suggestions?