简体   繁体   中英

How can we sort the result by date in Hibernate?

I am using Hibernate to fetch the JSON object from DB. I want that JSON object should contain all the details of the only top two of most recently created VGIs. But I don't know how to limit the result set and then sort on the basis of created date when no HQL query is used. It is fetching all the details from MySQL db.

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "vgi", catalog = "coworkee5")
public class VGI {
@ManyToOne
@JoinColumn(name = "employee_id", referencedColumnName = "id", insertable = false, updatable = false)
private Employees employees;

public Employees getEmployees() {
    return employees;
}

public void setEmployees(Employees employees) {
    this.employees = employees;
}

@OneToMany(cascade = CascadeType.ALL, targetEntity = VgiGoals.class, mappedBy = "vgi")
private List<VgiGoals> vgiGoals;

public List<VgiGoals> getVgiGoals() {
    return vgiGoals;
}

public void setVgi_goals(List<VgiGoals> vgiGoals) {
    this.vgiGoals = vgiGoals;
}

public VGI() {
}

@Id
@Column(name = "id")
private String id;
@Column(name = "title")
private String vgi;
@Column(name = "employee_id")
private String employee_id;
@Column(name = "created_on")
private String created;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getvgi() {
    return vgi;
}

public void setvgi(String vgi) {
    this.vgi = vgi;
}

public String getEmployee_id() {
    return employee_id;
}

public void setEmployee_id(String employee_id) {
    this.employee_id = employee_id;
}


public String getCreated() {
    return created;
}

public void setCreated(String created) {
    this.created = created;
}

}

Add @OrderBy annotation to sort like below.

@OneToMany(cascade = CascadeType.ALL, targetEntity = VgiGoals.class, mappedBy = "vgi")
@OrderBy("createdOn DESC")
private List<VgiGoals> vgiGoals;

NOTE : replace createdOn with your date field in VgiGoals class.

And for limit use below method in the query.

query.setFirstResult(1).setMaxResults(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM