Here are two solutions, both of which involve the @OrderBy annotation:
http://openjpa.apache.org/docs/latest/manual/jpa_overview_meta_field.html#jpa_overview_meta_orderby
(1) If your Entities themselves contain a column on which you'd like to
sort, then use the @OrderBy annotation on the collection field:
@Entity
public class MyEntity
{
...
@OneToMany()
@OrderBy("sortField") // MySortableEntity.sortField
Collection<MySortableEntity> sortedCollection;
...
}
(2) If your Entities do not (or cannot) contain an extra field to
support sorting, then you can create a separate Entity (a glorified join
table) to reference original entities and contain sort info:
@Entity
public class MyEntity
{
...
@OneToMany()
@OrderBy("sortField") // MySortableProxy.sortField
Collection<MySortableProxy> sortedCollection;
...
}
@Entity
public class MySortableProxy
{
...
@ManyToOne
protected MyUnsortableEntity entity;
@Basic
protected long sortField;
...
}
I'd written to this list a while back about some related issues:
http://www.nabble.com/question-on-orderby-and-manytomany-td14822597.html
http://www.nabble.com/safe-to-%22reuse%22-table-for-mapping-of-separate-entities-relations--td15095287.html
Cheers,
Andy
os_developer wrote:
Hi,
I wasn’t able to find a previous thread that answers
this although it does sound a bit familiar to
me...feel free to refer me to a prior thread if I’m
repeating...
My goal is to be able to be able to persist a
Collection of data in a particular order (and maintain
that order when I retrieve it) and I’m hoping that
someone may be able to tell me if I am going about
this the correct way. For example, if I have a list
B-C-A, I want to persist it and then later retrieve
that list in the same order. The data itself isn’t
something I can just add an "order by" clause to as
the order is more time dependent.
I’ve used an orm.xml and the ReverseMappingTool to
generate my code, but even when I change the default
collection implementation to use an ordered or sorted
collection, I don’t get the expected results. Perhaps
I’m just implementing the collection usage wrong or
this is a feature not intended to be supported in JPA?
I’d rather not modify my database schema but so far
that’s where I feel like this is leading me.
Any suggestions?
Thanks, in advance, for any help you can offer.
Andrea
____________________________________________________________________________________
Be a better friend, newshound, and
know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ