Framework used: Spring
ORM used: Hibernate
I have two classes
class BatchExceptionDetails{
...
private Set<BatchExceptionComments> batchExceptionComments;
}
class BatchExceptionComments implements Comparable<BatchExceptionComments>{
...
@Override
public int compareTo(BatchExceptionComments o) {
// TODO Auto-generated method stub
return this.getAddedOn().compareTo(o.getAddedOn());
}
}
They are mapped with one to many mapping.
There is a set of BatchExceptionComments in BatchExceptionDetails.
I want to sort the set on the basis of Date. BatchExcpetionComment has an attribute of type java.util.Date i.e. addedOn. I want the latest comment to be the first element of set.
The set I am receiving is not sorted. Will you please guide me where I am going wrong.
Thanks in advance
Set
is an interface, so it is not possible to establish if it is sortable or not. You have to use the correct implementation, like TreeSet. If you want to
emphasize that it is a sorted set, you should use the SortedSet
interface. TreeSet
implements SortedSet
.
Alternatively you can use a List
and then you can sort it using Collections.sort
.
After some goofing around I found a solution.
I just declared the set
private Set<BatchExceptionComments> batchExceptionComments;
Instead of using Comparable I used Order By to arrange the set.
<set name="batchExceptionComments" table="BATCH_EXCEPTION_COMMENTS"
inverse="true" fetch="select" lazy="false" order-by="commentId">
<key>
<column name="EXCEPTION_ID" not-null="true" />
</key>
<one-to-many class="com.beans.BatchExceptionComments" />
</set>
I believe ordering by Id will be better.
P.S. I am using hbm.xml instead of annotation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With