Is it possible to select data with the maximum value for a column using criteria in sleep mode?

Suppose I have the following mapping:

<hibernate-mapping package="mypackage">
    <class name="User" table="user">
  <id name="id" column="id">
   <generator class="native"></generator>
  </id>        
  <property name="name" />
  <property name="age" />
  </class>
</hibernate-mapping>

Can I select the oldest user (maximum age) using the criteria in sleep mode?

I can imagine that I could do this with two options. (first select the total number of users, and then order the entries by age and select the first entry). But is this possible with one choice?

thank

Fell

+3
source share
2 answers

With the Criteria API, you can do this as follows:

session.createCriteria(User.class).addOrder(Order.desc("age")).setMaxResults(1)
+5
source

. , . .

User oldest = getSession().createQuery("SELECT u FROM User u ORDER BY u.age DESC")
    .setMaxResults(1).uniqueResult();
+1

Source: https://habr.com/ru/post/1737703/


All Articles