February 26, 2022

Spring Data JPA @Query Annotation Example

In the Spring Data JPA Example we have already seen an integrated example of Spring Rest Controller + JPA (Hibernate) + MySQL. In that example query look up strategy for user defined query was automatic where Spring framework did the work of deriving query by parsing the method name. Though getting a query derived from the method name is quite convenient but you may face the situation where method name parser does not support the keyword you used or the method name would get unnecessarily ugly. In that case Spring Data JPA provides two options-

  • You can use JPA named queries using @NamedQuery annotation.
  • Annotate your query method with @Query.

In this article we'll see Spring data JPA example with @Query annotation.

For Spring Data JPA example using @NamedQuery annotation check this post- Spring Data JPA @NamedQuery Annotation Example

Spring Data JPA with @Query annotation

we’ll create a rest web service using Spring Web MVC, JPA implementation used is Hibernate and DB is MySQL.

The example shows the use of the @Query annotation. Advantage of using Spring Data JPA @Query annotation is that it is applied on the query method in the repository interface rather than annotating them to the domain class. This will free the domain class from persistence specific information and place the query in the repository interface itself.

Note that queries annotated to the query method using @Query will take precedence over queries defined using @NamedQuery or named queries defined in XML using <named-query /> element.

Maven dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- Spring data JPA -->
    <!-- Hibernate -->
    <!-- MySQL Driver -->

Dependencies are added for Spring core, Spring context as well as for Spring Web and Spring data JPA.

Dependency for Hibernate is added as Hibernate JPA implementation is used.

MySQL connector is used for connecting to MySQL DB from Java application.

Jackson databind is needed for webservice responses which are sent as JSON.

DB table Query

MySQL DB table used for this Spring data JPA can be created using the following query.

CREATE TABLE `employee` (
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `department` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)

Spring data JPA example – Entity class

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

public class Employee {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;
  private String firstName;
  private String lastName;
  private String dept;
  public int getId() {
    return id;
  public void setId(int id) {
    this.id = id;
  public String getFirstName() {
    return firstName;
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  public String getLastName() {
    return lastName;
  public void setLastName(String lastName) {
    this.lastName = lastName;
  public String getDept() {
    return dept;
  public void setDept(String dept) {
    this.dept = dept;

  public String toString() {
    return "Id= " + getId() + " First Name= " + 
             getFirstName() + " Last Name= " + getLastName() + 
             " Dept= "+ getDept();

This is the entity class which maps to the employee table in DB.

@Entity annotation specifies that this model class is an entity.

@Table annotation specifies the primary table for the entity.

@Id annotation specifies the primary key of the entity.

@GeneratedValue specifies the primary key generation strategy which is autoincrement in this case.

@Column annotation specifies the mapped table column name for the field.

Spring Data JPA Repository

import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.knpcode.springproject.model.Employee;

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
  List<Employee> findByLastName(String lastName);

  @Query("select e from Employee e where e.dept = ?1")
  List<Employee> findByDepartment(String department);

EmployeeRepository interface extends CrudRepository which takes the domain class to manage (Employee in this case) as well as the id type of the domain class as type arguments.

Apart from the methods inherited from CrudRepository there are two methods defined in EmployeeRepository inerface-

Method findByDepartment() has a query annotated with the method using @Query annotation so that query is used for the method rather than deriving query.

For method findByLastName Spring data derives a query using the method name.

Spring Data JPA example – Service class

From the service layer we’ll call the repository methods. Notice that repository instance has to be injected in the service class.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.knpcode.springproject.dao.EmployeeRepository;
import com.knpcode.springproject.model.Employee;

public class EmployeeService {
  private EmployeeRepository repository;

  public Employee getEmployeeById(int id) {
    return repository.findById(id).get();

  public List<Employee> getAllEmployees(){
    return (List<Employee>) repository.findAll();

  public void deleteEmployeeById(int id){

  public Employee addEmployee(Employee emp) {
    return repository.save(emp);

  public List<Employee> getEmployeeByLastName(String lastName) {
    return repository.findByLastName(lastName);

  public List<Employee> getEmployeeByDepartment(String department) {
    return repository.findByDepartment(department);

Rest Controller

Using a Rest controller class we’ll map the path to the methods that are to be called for the requests.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.knpcode.springproject.model.Employee;
import com.knpcode.springproject.service.EmployeeService;

public class EmployeeController {
  EmployeeService empService;
  public Employee getEmployeeById(@PathVariable int id) {
    return empService.getEmployeeById(id);
  public List<Employee> getAllEmployees(){
    return empService.getAllEmployees();
  public void deleteEmployeeById(@PathVariable int id){
  public Employee addEmployee(@RequestBody Employee emp) {
    return empService.addEmployee(emp);
  public List<Employee> getEmployeeByLastName(@PathVariable String lastName) {
    return empService.getEmployeeByLastName(lastName);
  public List<Employee> getEmployeeByDepartment(@PathVariable String department) {
    return empService.getEmployeeByDepartment(department);

Spring Data JPA – configuration classes

In this Spring data JPA example Java configuration is used so class is annotated with @Configuration annotation.

For setting up DataSource DB properties are read from a properties file, path for the properties file is configured using @PropertySource annotation.

@EnableJpaRepositories annotation enables the JPA repositories. Package to scan for the repositories is provided as a value with this annotation.

@EnableTransactionManagement annotation enables Spring's annotation-driven transaction management capability.

With in this Java config class we set up a EntityManagerFactory and use Hibernate as persistence provider.

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableJpaRepositories(basePackages = "com.knpcode.springproject.dao", queryLookupStrategy=Key.CREATE_IF_NOT_FOUND)
public class JPAConfig {
  private Environment env;
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    return factory;

  public DataSource dataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
    return ds;

  Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", env.getProperty("hibernate.sqldialect"));
    properties.setProperty("hibernate.show_sql", env.getProperty("hibernate.showsql"));
    return properties;

  public PlatformTransactionManager transactionManager() {
    JpaTransactionManager txManager = new JpaTransactionManager();
    return txManager;

If you are using XML configuration then the configuration for enabling JPA repositories is-

<jpa:repositories base-package="com.knpcode.springproject.dao"/>
db.properties file

To set up the web application using Java config rather than using the web.xml we’ll need the following classes.

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return null;

  protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[] {WebConfig.class};

  protected String[] getServletMappings() {
    return new String[] {"/"};
@ComponentScan(basePackages = "com.knpcode.springproject")
public class WebConfig implements WebMvcConfigurer{


Deploying the Spring Data JPA application

Right clicking the project and select Run As – Maven build, provide goal as clean install. If the build is successful you will have your application packaged as a war which you can deploy on web container like Tomcat and then test the application.

For testing the RESTful webservice, Postman rest client is used.

Adding employee

Spring Data JPA Example

Note that the request selected is POST and the URL is http://localhost:8080/SpringJPAProject/employee

Data is sent as request body in JSON format. In the response added Employee data is sent back.

Find by department (@Query annotated query method)

Spring data @Query

Get Employee by last name

You can also also send requests directly from browser as done for this request.

spring data

That's all for the topic Spring Data JPA @Query Annotation Example. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment