Search code examples
hibernatecriteriahibernate-criteria

Getting two unique results from same row using Hibernate Criteria


Is it possible to get two unique results from the same table using Hibernate Criteria? For instance, what if I'd like to query the most recent type of vehicle (a truck or a car).

Criteria criteria = getCurrentSession().createCriteria(Vehicle.class);
criteria.add(Restrictions.eq("vehicleType", "car"));  // notice how I want a unique car AND truck
criteria.add(Restrictions.eq("vehicleType", "truck"));
criteria.add(Restrictions.le("date", date));
criteria.addOrder(Order.desc("date"));
criteria.setMaxResults(2);
Object result = criteria.uniqueResult(); // Possible to get most recent unique car and truck?

I'd like to do this in one query because I assume one query to the database will be faster than two queries to the database.

So to rephrase my question, how can I get the most recent car and the most recent truck in one Hibernate Criteria Query. Assume that car and truck are represented as decimals so the table can be sorted by vehicleType.

To be even more specific, I'd like to do this using hibernate.


Solution

  • In the end I found out that I can make a native SQL Query using Hibernate.

    For example:

    getCurrentSession().createSQLQuery("SELECT * FROM Vehicle").list();
    

    The downside to this is that Hibernate returns an Object[] instead of the an Object of type Vehicle (in the example above).