darrachequesne / spring-data-jpa-datatables

Spring Data JPA extension to work with the great jQuery plugin DataTables (https://datatables.net/)
Apache License 2.0
447 stars 173 forks source link

Example of Specification<T> additionalSpecification #5

Closed jcworklooks closed 8 years ago

jcworklooks commented 8 years ago

Hi, First of all, thanks for wonderful spring based solution for datatables.

Can you please provide an example for below situation. Suppose I have OnetoMany relation in Employer/Employee. What if I want to show all employees related to one employer only using employer id? How do I configure Specification additionalSpecification with Employer id as PathVariable/Get Param? for example /abc/employees/{employerId} or /abc/employees?id=12312 Can we set employer Id each time request is sent to server in case of search and pagination? I have many such cases in which a datatable need to be shown on page load.

Thanks in advance.

darrachequesne commented 8 years ago

Hi! The simplest way to achieve what you describe would be (I think) to add a hidden column, something like that:

$('#example').dataTable( {
  'columns': [
    { 
       data: 'employer.id',
       name: 'employerId',
       visible: false
    },
    ...
  ]
} );

and then apply your filter on that hidden column. Of course, in that case, the client has the control over the employerId sent to the server. If you want to apply it on the server-side:

public static Specification<Employee> withEmployerId(Integer employerId) {
    return (root, query, criteriaBuilder) -> {
        return criteriaBuilder.equals(
            root.join(Employee_.employer).get(Employer_.id), 
            employerId);
    };
}
// not tested, but that should work!
darrachequesne commented 8 years ago

Closing this now, please reopen if it didn't solve your issue. :angel: