我正在将Spring Data Rest用于Department-Employee关系,如下所示,并且在Employee上定义了RepositoryRestResource。
class Department {
@Id
UUID Id;
String name;
@OneToMany(mappedBy = "employee", targetEntity = Employee.class, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@RestResource(exported = false)
private Set<Employee> employees;
}
class Employee {
@Id
UUID Id;
String firstName;
String lastName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dept_ref")
@RestResource(exported = false)
private Department department;
}
@Projection(name = "employeeProjection", types = {Employee.class})
interface EmployeeProjection {
String getFirstName();
String getLastName();
}
@RepositoryRestResource(excerptProjection = EmployeeProjection.class)
public interface EmployeeRepository extends CrudRepository<Employee, UUID> {
//this doesn't work
@Query(value = "SELECT emp.firstName as firstName , emp.lastName as lastName FROM Employee emp JOIN emp.department "
+ "WHERE emp.department.name = :departmentName ")
List<EmployeeProjection> findByDepartmentName(@Param("departmentName") String departmentName);
//this works
List<EmployeeProjection> findByFirstName(@Param("firstName") String firstName);
}
问题是当我以findByDepartmentName执行联接搜索时,出现以下错误。
2019-07-01 00:26:33.300 ERROR 7396 --- [nio-8443-exec-5] o.s.d.r.w.RepositoryRestExceptionHandler : PersistentEntity must not be null!
java.lang.IllegalArgumentException: PersistentEntity must not be null!
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.springframework.data.rest.webmvc.PersistentEntityResource$Builder.<init>(PersistentEntityResource.java:140)
答案 0 :(得分:0)
通过将返回类型从List<Employee>
更改为List<EmployeeProjection>
来解决了问题,它仍然以excerptProjection
的形式返回投影。不知道为什么Spring Data Rest会期望这样做,但是它可以工作。
List<Employee> findByDepartmentName(@Param("departmentName") String departmentName);