Rafael Orágio
Rafael Orágio

Reputation: 1788

Get lazy list ordered by column

This is my simple situation:

@Entity
@Table(name = "project")
public class Project implements Serializable {

    @Id
    private Long id;

    @OneToMany(mappedBy = "project")
    private List<Author> authors;

    public List<Author> getAuthors() {
        return authors;
    }
}

public class DAO {

    public void getOrderedAuthorsByProject(Project project) {
        return project.getAuthors(); // Line 1
    }
}

In the line 1, how return the author list, ordered by specific column of Author entity, simply doing a get?

Thanks.

Upvotes: 2

Views: 1979

Answers (1)

Alan Hay
Alan Hay

Reputation: 23246

If the property you wish to sort on is a field in Author (i.e. is a column in the Authors table) then you can use @OrderBy:

@OneToMany(mappedBy = "project")
@OrderBy("surname, forename asc")
private List<Author> authors; 

If it was a nested property then you can use the (Hibernate specific, non JPA) @Sort annotation to do an in-memory sort. You can either specify a Comparator or specify SortType = NATURAL if your Author entity implements the Comparable interface.

http://java.dzone.com/news/sorting-collections-hibernate

Upvotes: 3

Related Questions