我在通过子对象 ID、Example 和 Pageable 查询存储库时遇到问题。
StudentController.java
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(method = RequestMethod.GET)
public Page<Student> getStudentsPage(
@PageableDefault(page = 0, size = 10) @SortDefault.SortDefaults({
@SortDefault(sort = "id", direction = Direction.DESC) }) Pageable pageable,
Student student) {
return studentService.getStudentPage(student, pageable);
}
}
学生服务.java
@Service
public class StudentService {
private static final Logger logger = LoggerFactory.getLogger(StudentService.class);
@Autowired
private UserService userService;
@Autowired
private StudentRepository studentRepository;
public Page<Student> getStudentsPage(Student student, Pageable pageable) {
logger.debug("Getting Students : {}, {}", student, pageable);
//gets organization Id of the student from the session
String organizationId = userService.getUserMe().getOrganization().getId();
Page<Student> studentPage = studentRepository.findAllByOrganizationId(organizationId, Example.of(student), pageable);
logger.debug("Students: {}", studentPage.getContent());
return studentPage;
}
}
StudentRepository.java
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
Page<Student> findAllByOrganizationId(String organizationId, Example<Student> example, Pageable pageable);
}
学生.java
@Document(collection = "students")
public class Student {
@Id
private String id;
private String firstName;
private String lastName;
@DBRef(db = "organizations")
private Organization organization;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", organization="
+ organization + "]";
}
}
组织.java
@Document(collection = "organizations")
public class Organization {
@Id
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Organization [id=" + id + ", name=" + name + "]";
}
}
GET API 请求:http://localhost:8080/students?page=0&size=10&sort=id,desc&lastName=xyz
存储库方法 Page findAllByOrganizationId(String organizationId, Example example, Pageable pageable); 应该返回与组织 ID 和 lastName=xyz 匹配的所有记录,但它会返回与组织 ID 匹配的记录以及所有学生,而与姓氏无关。
代码有问题吗?