0

I have a JPA repository for a DB entity as follows:

@Repository
public interface StudentRepository
    extends  JpaRepository<Student, String>  {
}

Student entity is as follows:

@Entity
@Table(name = "student")
public class Student implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(generator = "custom-uuid")
  @GenericGenerator(name = "custom-uuid",
      strategy = "generator.CustomUUIDGenerator")
  private String id;

  @Column(name = "roll_number")
  private String rollNumber;

  @Column(name = "name")
  private String name;

  @LastModifiedDate
  @Column(name = "last_modified_date")
  @JsonIgnore
  private Instant lastModifiedDate = Instant.now();

Now, I would like to write the following SQL query using JPA as follows:

SELECT id, roll_number from  student where id=<id> order by last_modified_date desc;

Being new to JPA/Hibernate, I don't have an idea how to achieve this using JPA/Hibernate.

Could anyone please help here ?

2 Answers 2

1

You could write something like:

String hql = "SELECT s.id, s.rollNumber FROM Student s WHERE s.id = :id ORDER BY s.lastModifiedDate DESC";
query.setParameter("id", 10);
Query query = session.createQuery(hql);
List results = query.list();

Refer: https://www.tutorialspoint.com/jpa/jpa_jpql.htm

Sign up to request clarification or add additional context in comments.

Comments

0

Create a new method in Repository

@Repository
public interface StudentRepository extends JpaRepository<Student, String> {

    /**
     * List all student by criterias.
     *
     * @return
     */
    @Query(value = "SELECT id, roll_number from student where id=?1 order by last_modified_date desc;", nativeQuery = true)
    List<Student> listStudent(String id);

}

Reference document: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.