Close

Spring Data JPA - Web Support, resolving entity instances from request parameters or path variables

[Updated: Jun 11, 2018, Created: Jun 11, 2018]

Spring Data Web support can be enabled by using the @EnableSpringDataWebSupport annotation in our JavaConfig configuration class.

The @EnableSpringDataWebSupport annotation registers a few components in the background to provide the web support. In this example we will understand the support provided by DomainClassConverter. This converter let Spring MVC resolve instances of repository-managed domain classes from request parameters or path variables.

Example

pom.xml

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>2.0.7.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.6.RELEASE</version>
</dependency>
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.5</version>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.0.1</version>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.3.1.Final</version>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.197</version>
</dependency>

Domain class (JPA entity)

@Entity
public class Employee {
  private @Id
  @GeneratedValue
  Long id;
  private String name;
  private String dept;
  private int salary;
    .............
}

Spring Data Repository

public interface EmployeeRepository extends CrudRepository<Employee, Long> {
}

MVC controller

@RestController
public class EmployeeController {

  @GetMapping("/employees/{id}")
  public Employee getEmployeeById(@PathVariable("id") Employee employee) {
      return employee;
  }

  @GetMapping(value = "/employees")
  public Employee getEmployeeById2(@RequestParam("id") Employee employee) {
      return employee;
  }
}

The above handler methods will receive the fully initialized Employee instance by id directly, without any manual repository method call. In the background EmployeeRepository#findById() will be used to get the required entity instance.

Java config class

@ComponentScan
@Configuration
@EnableWebMvc
@EnableJpaRepositories
@EnableSpringDataWebSupport
public class AppConfig {

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      LocalContainerEntityManagerFactoryBean factory =
              new LocalContainerEntityManagerFactoryBean();
      factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
      return factory;
  }

  @Bean
  public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
      JpaTransactionManager txManager = new JpaTransactionManager();
      txManager.setEntityManagerFactory(entityManagerFactory);
      return txManager;
  }
}

Persisting some test Data

In this class we are persisting some test data during startup.

@Component
public class DataInitializer {
  @Autowired
  private EmployeeRepository repository;

  @PostConstruct
  void postConstruct() {
      repository.saveAll(createEmployees());
  }

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

Running

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

localhost:8080/employees/1

localhost:8080/employees?id=2

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.0.7.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-co1ntext version 5.0.6.RELEASE
  • spring-webmvc 5.0.6.RELEASE: Spring Web MVC.
  • jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
  • javax.servlet-api 3.0.1 Java Servlet API
  • 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

Spring Data JPA web support Example Select All Download
  • spring-data-jpa-domain-class-converter
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeController.java
          • resources
            • META-INF

    See Also