Skip to content

Instantly share code, notes, and snippets.

@jnizet
Created July 21, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnizet/dc8d6f78f97a70e3c7ecf13c839fe234 to your computer and use it in GitHub Desktop.
Save jnizet/dc8d6f78f97a70e3c7ecf13c839fe234 to your computer and use it in GitHub Desktop.
package com.example.demo;
public class Employee {
}
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping
public ResponseEntity<List<Employee>> findEmployees(@RequestParam("firstName") String firstName) {
List<Employee> employees = employeeService.findAllCustomersByFirstName(firstName);
return new ResponseEntity<>(employees, HttpStatus.OK);
}
}
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface EmployeeRepository extends JpaRepository<Employee, Long>, JpaSpecificationExecutor<Employee> {
}
package com.example.demo;
import java.util.List;
public interface EmployeeService {
List<Employee> findAllCustomersByFirstName(String firstName);
}
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public List<Employee> findAllCustomersByFirstName(String firstName) {
return employeeRepository.findAll(EmployeeSpecification.textInAllColumns(firstName));
}
}
package com.example.demo;
import javax.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;
public class EmployeeSpecification {
public static Specification<Employee> textInAllColumns(String text) {
if (!text.contains("%")) {
text = "%" + text + "%";
}
final String finalText = text;
return (root, query, builder) -> builder
.or(root.getModel().getDeclaredSingularAttributes().stream().filter(a -> {
return a.getJavaType().getSimpleName().equalsIgnoreCase("string") ? true : false;
}).map(a -> builder.like(root.get(a.getName()), finalText)).toArray(Predicate[]::new));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment