Spring Data JPA @Query Annotation

Let’s see Spring Data Jpa @Query Annotation Example. How to write query methods using @Query annotation.

@Query annotation used with repository methods.

Consider we have an entity called Student.java as below.

package com.netsurfingzone.entity;
 
@Entity
public class Student {
 
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
 
	@Column(name = "name")
	private String name;
 
	@Column(name = "roll_number")
	private String rollNumber;
 
	@Column(name = "university")
	String university;
	 
}

and we have some record in the database as below.

Spring Data JPA @Query Annotation

 

Let’s start with some code snippet which shows how to write a query using Spring Data Jpa @Query.


Writing Native Query using Spring Data Jpa @Query.

@Query(value = "select * from student where name = ?1",nativeQuery = true)
List<Student> getStudents(String name);

Note – For native query, we need to specify nativeQuery = true.

See a complete example from scratch here.

Writing JPQL using Spring Data Jpa @Query.

@Query("select s from Student s where s.name = ?1")
List<Student> getStudents(String name);


See a complete example from scratch here.

Writing the Named Parameter using Spring Data Jpa @Query.

@Query("select s from Student s where s.name = :name")
List<Student> findByName(@Param("name") String name);

See a complete example from scratch here.

Note – The above methods will return the list of student for the corresponding name.

 

That’s all about Spring Data JPA @Query Annotation.

You may like.

Other Spring Data JPA and Hibernate tutorials.


 

Spring Data JPA Docs.

Summary – We have seen different ways to define query methods using @Query annotation.