tags:

views:

175

answers:

3

I have the Vehicles class and mapping file for it and i want to get all rows from vehicles table ordered by ID desc (I also need the same for my other tables).

I got the following code:

session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();

q = session.createQuery("from Vehicles order by ID DESC");

    for (Iterator it=q.iterate(); it.hasNext();){
         //some logic
    }

But my set isn't ordered by ID and each time it has a different order like RAND() or something. I was wondering what is the easiest way to keep the functionality and just to add order by clause because I have the same syntax on many places...

A: 

Have you tried "from Vehicles v order by v.id desc"? Also another option is to add the comparable interface to the entity and then bring the list created by the query into a sortedset. That's typically what I do when I need to sort.

qbn
Yeas I did, not working...Is there any other way because I will need a lot of time to add comparable interface to all my classes and I will need to do some other changes in code...
Splendid
+1  A: 

I'm assuming your vehicles class looks like this? I'm using JPA here because thats what I know...

class Vehicles {
    @Id
    @Column(name="vehicles_id")
    private int id;
    // other stuff here
}

I don't expect your session.createQuery to be different from mine so wouldn't something like this work?

Query q = session.createQuery("select v from Vehicles v order by v.id desc");

Also you could use criteria if you wanted yeah?

class Main {
    List<Vehicles> cars;
}

Criteria main = session.createCriteria(Main.class);
Criteria secondary = main.createCriteria("cars");
secondary.addOrder(Order.asc("id"));
Petriborg
+1  A: 

Try after "q = session.createQuery(...);" part:

List results = q.list()
//loop through results

There is probably something wrong elsewhere, because "sort by id desc" part is correct. Check your database/mapping files if you have correct data types and if indexes are set properly.

serg