users@glassfish.java.net

Re: How to Sort / OrderBy _at_OneToMany

From: <glassfish_at_javadesktop.org>
Date: Mon, 17 Sep 2007 20:01:17 PDT

Here is the deal.

You are responsible for maintaining the Attributes relationships in the Attributes collection (List). When you create a new Objectattributes entity instance, you must insert it into the Attributes List and if you do not have the cascade annotation set to at least Cascade.PERSIST, you must also call EntityManager.persist() to persist this new Objectattributes entity instance as well.

When you insert the new Objectattributes entity instance into the Attributes list, if you want them toolkitName order, you (your code) must find the correct position in the Attributes List to add the new Objectattributes entity instance.

At a later point in time, if you retrieve a Objects entity instance using something like EntityManager.find(id), and the EntityManager actually goes to the persistent storage, it will create a Objects entity instance and when you call Objects.getAttributes(), a List of Objectattributes entities will be returned. This is the case where the "@OrderBy" come into play. When the EntityManager instantiates the List that Objects.getAttributes() will return, the List will be ordered by the "toolkitName" as specified in your "@OrderBy".

Now it may be that the EntityManager never goes to the persistance storage as the Objects entity instance that you are trying to retrieve is cached in memory, it will just return that cached instance so the "@OrderBy" will never come into play.

Think of it this way. If there was no persistence of the relationship between Objects and Objectattributes, who would maintain the List in the order that you want? If there is no EntityManager, then the only thing that could is your code. This is still the case. You must maintain the order of the Objectattributes entities in the Objects entity instance once they are in memory. The persistence manager will take care of the case of loading the Objects instance into memory from persistence storage and will ensure that your Objectsattributes are in the order specified by the "@OrderBy" when it does so. After that, it is up to your code to maintain he order.
[Message sent by forum member 'bbergquist' (bbergquist)]

http://forums.java.net/jive/thread.jspa?messageID=235734