Close

Spring Data JPA - Using SpEL Expression, #entityName

[Last Updated: Jun 11, 2018]

Spring supports the usage of restricted SpEL template expressions in manually defined queries that are defined with @Query.

In this tutorial, we will see the usage of variable entityName. It is used in query as shown in following example:

@Query("SELECT e FROM #{#entityName} e WHERE .... ")

The one of the advantages of the above as compared to the hard-coded entity name is, entityName is resolved dynamically.
As JPQL looks for the entity name either by looking at @Entity#name attribute (if that exists as specified in say, @Entity(name = "Emp")), or entity simple class name. That means from refactoring perspective (i.e. if we need to change the entity name via @Entity#name) then we don't have to update it manually every time in the query declared by @Query.

Example

Entity

@Entity(name = "emp")
public class Employee {
  private @Id
  @GeneratedValue
  Long id;
  private String name;
  private String dept;
  private int salary;
    .............
}

Repository interface

package com.logicbig.example;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

  @Query("SELECT e FROM #{#entityName} e WHERE e.dept = ?1")
  public List<Employee> findByDepartment(String deptName);
}

Example Client

@Component
public class ExampleClient {

  @Autowired
  private EmployeeRepository repo;

  public void run() {
      List<Employee> employees = createEmployees();
      repo.saveAll(employees);

      System.out.println(" -- finding all employees --");
      Iterable<Employee> all = repo.findAll();
      all.forEach(System.out::println);

      System.out.println(" -- finding by dept Admin  --");
      List<Employee> list = repo.findByDepartment("Admin");
      list.forEach(System.out::println);
  }

  private List<Employee> createEmployees() {
      return Arrays.asList(
              Employee.create("Diana", "Admin", 2000),
              Employee.create("Mike", "Sale", 1000),
              Employee.create("Rose", "IT", 4000),
              Employee.create("Sara", "Admin", 3500),
              Employee.create("Randy", "Sale", 3000),
              Employee.create("Charlie", "IT", 2500)
      );
  }
}

Main class

public class ExampleMain {

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      ExampleClient exampleClient = context.getBean(ExampleClient.class);
      exampleClient.run();
      EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
      emf.close();
  }
}
 -- finding all employees --
Employee{id=1, name='Diana', dept='Admin', salary=2000}
Employee{id=2, name='Mike', dept='Sale', salary=1000}
Employee{id=3, name='Rose', dept='IT', salary=4000}
Employee{id=4, name='Sara', dept='Admin', salary=3500}
Employee{id=5, name='Randy', dept='Sale', salary=3000}
Employee{id=6, name='Charlie', dept='IT', salary=2500}
-- finding by dept Admin --
Employee{id=1, name='Diana', dept='Admin', salary=2000}
Employee{id=4, name='Sara', dept='Admin', salary=3500}

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.0.7.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-context version 5.0.6.RELEASE
  • hibernate-core 5.3.1.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • h2 1.4.197: H2 Database Engine.
  • JDK 1.8
  • Maven 3.3.9

Using SpEL Expressions Select All Download
  • spring-data-jpa-spel-expression
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeRepository.java
          • resources
            • META-INF

    See Also