I have following Author entity. I wanted to print first group of (authors grouped by their age in descending order).
Eg,
Author
id name age
1 JK 20
2 NRN 25
3 APJ 35
4 RK 20
5 NRN 25
6 JK 20
7 RK 20
After sorting (ASC) it will be:
1 JK 20
4 RK 20
6 JK 20
7 RK 20
2 NRN 25
3 APJ 35
5 NRN 25
I wanted to have first set of grouping as the result, i.e,
1 JK 20
4 RK 20
6 JK 20
7 RK 20
I tried with following query but it returns all the results.
String hql = "FROM Author A ORDER BY A.age ASC";
Query query = session.createQuery(hql);
List results = query.list();
Please let me know what could be modified in the query.
@Entity
public class Author {
@Id
private int id;
private String name;
private int age;
public Author() {
}
public Author(int id, String name, int age) {
super();
this.setId(id);
this.setName(name);
this.setAge(age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Author [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Thanks.
Once try this code, it may help
List<Author> ages = session
.createNativeQuery("SELECT * FROM Author a WHERE a.age = (SELECT min(a.age) FROM Author a)")
.addEntity(Author.class).getResultList();