views:

245

answers:

2

I use Hibernate with Java.

I have two tables which are associated with foreign keys.

Table: country
Fields: ID, Name
POJO class name : Country
POJO class properties: id, name, cities

Table: city
Fields: ID, Name, CountryID
POJO class name : Country

Then I use "hibernate reverse engineering" of MyEclipse. It creates DAOs, abstracts and pojo classes automatically.

Everything works very well. When I request a Country object, Hibernate retrieves it and fills the property "cities" with cities which has CountryID as country.id.

Still everything fine but when I list "cities" property (java Set type), then print out IDs of all cities I got this unordered list:

ID: 5
ID: 1
ID: 4
ID: 2

Where should I edit to get cities ordered by ID when I obtain Country instances from the CountryDAO class?

+1  A: 

Are you using XML mapping, or annotations?

Usually, on mapped collections there is an "order-by" attribute that lets you specify a column to order the collection by, and asc or desc ordering.

See this page:

http://docs.jboss.org/hibernate/stable/core/reference/en/html/collections-mapping.html

Search for "order-by" - you'll need to find the appropriate collection mapping for your example.

Andy White
Andy, thanks for your consideration; however I still get exception about it. Could you check about what is wrong with it, please? http://pastebin.ca/1410416
Ahmet Alp Balkan
+3  A: 

You may try to use Hibernate's Criteria API to provide such a constraint. Following piece is going to order the posts by id ascending.

List posts = session.createCriteria(Post.class)
    .addOrder( Order.asc("id") )
    .list();
Burcu Dogan
It's been a while I haven't used Hibernate, please ignore syntax mistakes if there are any.
Burcu Dogan
great answer thanks
nimcap