Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data REST custom query integration

I want to create a REST link for an Employee entity that will basically be a findByAllFields query. Of course this should be combined with Page and Sort. In order to do that I have implemented the following code:

@Entity
public class Employee extends Persistable<Long> {

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Column
    private String age;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date hiringDate;
}

So I would like to have lets say a query where I can do:

http://localhost:8080/myApp/employees/search/all?firstName=me&lastName=self&ageFrom=20&ageTo=30&hiringDateFrom=12234433235

So I have the following Repository

 @RepositoryRestResource(collectionResourceRel="employees", path="employees")
 public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long>, 
                                                         JpaSpecificationExecutor<Employee> {

 }

Ok so now I need a RestController

@RepositoryRestController
public class EmployeeSearchController {

    @Autowired
    private EmployeeRepository employeRepository;

    @RequestMapping(value = "/employees/search/all/search/all", method = RequestMethod.GET)
    public Page<Employee> getEmployees(EmployeeCriteria filterCriteria, Pageable pageable) {

        //EmployeeSpecification uses CriteriaAPI to form dynamic query with the fields from filterCriteria
        Specification<Employee> specification = new EmployeeSpecification(filterCriteria);

        return employeeRepository.findAll(specification, pageable);
}

Ok, obviously this does its job but it is not integrated with HATEOAS. I have attempted to assemble a resource changing the controller to this:

public PagedResources<Resource<Employee>> getEmployees(
                PagedResourcesAssembler<Employee> assembler,
                EmployeeCriteria filterCriteria, Pageable pageable) {

        //EmployeeSpecification uses CriteriaAPI to form dynamic query with the fields from filterCriteria
        Specification<Employee> specification = new EmployeeSpecification(filterCriteria);

        Page<Employee> employees = employeeRepository.findAll(specification, pageable);
        return assembler.toResource(employees);
}

Obviously I'm missing something from the above since it doesnt work and I'm getting the following Exception:

Could not instantiate bean class [org.springframework.data.web.PagedResourcesAssembler]: No default constructor found;

Ok so to make the question clear I am trying to integrate the above resource into the rest of the HATEOAS architecture. I'm not entirely sure if this is the correct approach so any other suggestions are welcome.

EDIT: Here you can see a similar implementation. Please take a look at the configuration, you will see that all but one of the "Person" controllers are working. https://github.com/cgeo7/spring-rest-example

like image 713
ChrisGeo Avatar asked Sep 22 '14 18:09

ChrisGeo


People also ask

What is difference between JpaRepository and CrudRepository?

CrudRepository: provides CRUD functions. PagingAndSortingRepository: provides methods to do pagination and sort records. JpaRepository: provides JPA related methods such as flushing the persistence context and delete records in a batch.

Why is spring data rest not recommended in real world applications?

It is not recommended in real-world applications as you are exposing your database entities directly as REST Services. While designing RESTful services, the two most important things that we consider are the domain model and the consumers. But, while using Spring Data REST, none of these parameters are considered.

How do I create a custom query in spring boot?

We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using JPQL, Java Persistence Query Language. We've added name query custom methods in Repository in JPA Named Query chapter.


2 Answers

Try autowring PagedResourcesAssembler as a class member and change method signature something like below

@RepositoryRestController
public class EmployeeSearchController {

    @Autowired
    private EmployeeRepository employeRepository;

    @Autowired
    private PagedResourcesAssembler<Employee> pagedAssembler;

    @RequestMapping(value = "/employees/search/all/search/all", method = RequestMethod.GET)
    public ResponseEntity<Resources<Resource<Employee>>> getEmployees(EmployeeCriteria filterCriteria, Pageable pageable) {

        //EmployeeSpecification uses CriteriaAPI to form dynamic query with the fields from filterCriteria
        Specification<Employee> specification = new EmployeeSpecification(filterCriteria);

        Page<Employee> employees = employeeRepository.findAll(specification, pageable);
        return assembler.toResource(employees);
    }
}

This works perfectly with Spring Data Rest 2.1.4.RELEASE

like image 94
Stackee007 Avatar answered Oct 19 '22 22:10

Stackee007


The code by @Stackee007 works but the resource won't include self links. In order to do that, a little more is required.

@Autowired
PagedResourcesAssembler<Appointment> pagedResourcesAssembler;

@RequestMapping(value = "/findTodaysSchedule")
public HttpEntity<PagedResources<Resource<Appointment>>> getTodaysSchedule(
        PersistentEntityResourceAssembler entityAssembler, Pageable pageable) {
    Page<Appointment> todaysSchedule = apptRepo.findByStartTimeBetween(beginningOfDay, endOfDay, pageable);

    @SuppressWarnings({ "unchecked", "rawtypes" })
    PagedResources<Resource<Appointment>> resource = pagedResourcesAssembler.toResource(todaysSchedule,
                (ResourceAssembler) entityAssembler);

    return new ResponseEntity<>(resource, HttpStatus.OK);
}
like image 45
Abhijit Sarkar Avatar answered Oct 19 '22 23:10

Abhijit Sarkar