Search code examples
javajpaeclipselinkpostgresql-9.6

get latest record from table using postgresql


I have table employee as below,

id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102 

I am using jpa with eclipselink implementation and database is postgresql. Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always. Thanks,


Solution

  • You must add updatedDate field in the entity class.

    So I'll like to know if is there a SIMPLE way around my problem, meaning having @PrePersist or @PreUpdate or even other workaround to set the lastModified field still using session

    Entity Class:

    @Entity
    @Table(name = "employee")
    public class Employee {
    
        @Id
        @GeneratedValue
        private Long id;
    
    
        @Column(name = "name")  
        private String name;
    
        @Column(name = "number")  
        private Long number;
    
        @Column(name = "updated_at")  
        @Temporal(TemporalType.TIMESTAMP)  
        private Date updatedAt;  
    
        // getter setter
    
        @PreUpdate  
        public void setChangeDate() {  
           this.updatedAt = new Date();  
        }  
    
    }
    

    You can use JPA query. This exam:

    String query = "SELECT emp FROM Employee emp order by updatedAt desc limit 1 ";