Kulwant
Kulwant

Reputation: 681

Ordering a Set within a domain object

I am using Hibernate and JPA. I currently have reverse engineered DAO which gives me a list of all 50 States.

Within each state is a list of items. Set<Items>

The Items class has a property called name.

I need to return a list of States - Doesn't matter the order. But each item within the state needs to be returned in alphabetical order?

Here is the DAO.

public List<State> findAll() {
        EntityManagerHelper
                .log("finding all State instances", Level.INFO, null);
        try {
            final String queryString = "select model from State model";
            Query query = getEntityManager().createQuery(queryString);
            return query.getResultList();
        } catch (RuntimeException re) {
            EntityManagerHelper.log("find all failed", Level.SEVERE, re);
            throw re;
        }
    }

And here is the State

public class State implements java.io.Serializable {
    private Set<Item> items= new HashSet<Item>(0);
}

And this needs to be ordered by a property in the Item called Name.

Upvotes: 0

Views: 174

Answers (2)

digitaljoel
digitaljoel

Reputation: 26574

In general, a Set is unordered. There are implementations that will give a determinate iteration order like LinkedHashSet, but you should use a list if you want to maintain order. Even if the values are returned to Java in an ordered format, the order will not be preserved when you put them into a vanilla HashSet.

If you don't want to return the items in order, you should look into implementing the Comparable interface for your State object, or implementing a Comparator that will look at the Name property of the State to evaluate order.

Upvotes: 2

lschin
lschin

Reputation: 6811

You may use the JPA annotation javax.persistence.OrderBy.

For example :

public class State {
    private Set<Item> items= new HashSet<Item>(0);

    @OneToMany(mappedBy = "state")
    @OrderBy("name")
    public Set<Item> getItems() {
        return items;
    }

    // Setter
}

Upvotes: 0

Related Questions