views:

339

answers:

4

Is there a Hibernate configuration (hopefully an annotation on a classes mapped @Column field) that would let me sort a collection of entities associated with the loaded entity by a given column of that entity when a session.load(Entity.class, Id) is called?

For example if I had an EntityA that contained a OneToMany association to an EntityB.

@Entity
public class EntityA {
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY) 
    private Set<EntityB> headlines = new TreeSet<Entity>();

}

I want EntityB to be sorted in the Set that is returned from Hibernate.

A: 

session.load() loads a single entity instance. No sorting is involved.

Update (based on question edit):

@OrderBy("column_name") can be used to sort collection elements within entity by given column; however that only makes sense for collections that maintain their order (e.g. List, not Set):

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY) 
@OrderBy("name")
private List<EntityB> headlines = new ArrayList<Entity>();
ChssPly76
I used a SortedSet and used the @Sort annotation (but someone on stackoverflow thought that was a bad answer, any idea why?)
Dougnukem
A: 

No. You can select ordering only on collection level (@OrderBy) or throug hql or criteria api.

pepiino
+1  A: 

Session.load does not load a list, only a single object.

You can sort a list of entities when you retrieve them from the database by using the addOrder() method on the criteria.

If you have a parent class with a list of children, you can order the children with the @OrderBy annotation (see Hibernate Annotations - Collections

Rachel
A: 

I used @Sort and a SortedSet collection to map my association which required that my Entity implement Comparable interface (int compareTo(T) method).

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@Sort(type=SortType.NATURAL)    
private SortedSet<Entity> headlines = new TreeSet<Entity>();
Dougnukem
any reason why this is a bad solution?
Dougnukem