我想为一个名为Employee
的实体创建一个REST链接,它将基本上是一个findByAllFields
查询。当然,这应该与Page
和Sort
相结合。为了做到这一点,我已经实现了以下代码:
@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;
}
所以我想要一个查询,例如我可以执行:
http://localhost:8080/myApp/employees/search/all?firstName=me&lastName=self&ageFrom=20&ageTo=30&hiringDateFrom=12234433235
所以我有以下 Repository
@RepositoryRestResource(collectionResourceRel="employees", path="employees")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long>,
JpaSpecificationExecutor<Employee> {
}
好的,现在我需要一个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);
}
好的,显然这个功能可以实现,但它没有与HATEOAS集成。 我尝试重新组装资源将控制器更改为以下内容:
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);
}
显然,从上面的内容来看我漏掉了什么,因为它没有起作用,我得到了以下异常:
Could not instantiate bean class [org.springframework.data.web.PagedResourcesAssembler]: No default constructor found;
好的,为了让问题更清晰,我正在尝试将上述资源集成到HATEOAS架构的其余部分中。我不确定这是否是正确的方法,所以欢迎任何其他建议。
编辑: 在这里,您可以看到类似的实现。请查看配置,您会发现除了一个“Person”控制器之外,其他所有控制器都在工作。 https://github.com/cgeo7/spring-rest-example