Spring Data MongoDB:使用Example Executor和Pageable查找所有子对象ID。

huangapple go评论79阅读模式
英文:

Spring data mongoDB : Find all by child object id with Example Executor and Pageable

问题

I am facing issue in querying repository with find all by child object ID, Example and 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);
    } 
}

StudentService.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);
}

Student.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;
    }
    
    // ... (other getters and setters)
}

Organization.java

```java
@Document(collection = "organizations")
public class Organization {
    @Id
    private String id;
    private String name;
    
    // ... (getters and setters)
}

The GET API request:
http://localhost:8080/students?page=0&size=10&sort=id,desc&lastName=xyz

The repository method findAllByOrganizationId(String organizationId, Example<Student> example, Pageable pageable) should return all the records with matching organizationId and lastName=xyz, but it returns the records that match with the organization Id along with all the students irrespective of the lastName.

Is something wrong with the code?

英文:

I am facing issue in querying repository with find all by child object ID, Example and Pageable.

StudentController.java

@RestController
@RequestMapping(&quot;/students&quot;)
public class StudentController {
    @Autowired
    private StudentService studentService;
    
    @RequestMapping(method = RequestMethod.GET)
    public Page&lt;Student&gt; getStudentsPage(
            @PageableDefault(page = 0, size = 10) @SortDefault.SortDefaults({
                    @SortDefault(sort = &quot;id&quot;, direction = Direction.DESC) }) Pageable pageable,
            Student student) {
        return studentService.getStudentPage(student, pageable);
    } 
}

StudentService.java

@Service
public class StudentService {
    private static final Logger logger = LoggerFactory.getLogger(StudentService.class);    
    @Autowired
    private UserService userService;
    
    @Autowired
    private StudentRepository studentRepository;
    
    public Page&lt;Student&gt; getStudentsPage(Student student, Pageable pageable) {
        logger.debug(&quot;Getting Students : {}, {}&quot;, student, pageable);
        //gets organization Id of the student from the session
        String organizationId = userService.getUserMe().getOrganization().getId(); 
        Page&lt;Student&gt; studentPage = studentRepository.findAllByOrganizationId(organizationId, Example.of(student), pageable);
        
        logger.debug(&quot;Students: {}&quot;, studentPage.getContent());
        return studentPage;
    }
}

StudentRepository.java

@Repository
public interface StudentRepository extends MongoRepository&lt;Student, String&gt; {    
    Page&lt;Student&gt; findAllByOrganizationId(String organizationId, Example&lt;Student&gt; example, Pageable pageable);
    
}

Student.java

@Document(collection = &quot;students&quot;)
public class Student {
    @Id
    private String       id;
    private String       firstName;
    private String       lastName;
    @DBRef(db = &quot;organizations&quot;)
    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 &quot;Student [id=&quot; + id + &quot;, firstName=&quot; + firstName + &quot;, lastName=&quot; + lastName + &quot;, organization=&quot;
               + organization + &quot;]&quot;;
    }
    
}

Organization.java

@Document(collection = &quot;organizations&quot;)
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 &quot;Organization [id=&quot; + id + &quot;, name=&quot; + name + &quot;]&quot;;
    }
    
}

The GET API request:
http://localhost:8080/students?page=0&size=10&sort=id,desc&lastName=xyz

the repository method
Page<Student> findAllByOrganizationId(String organizationId, Example<Student> example, Pageable pageable);
should return all the records with matching organizationId and lastName=xyz, But it returns the records that match with the organization Id along with all the students irrespective of the lastName.

Is something wrong with the code?

答案1

得分: 0

Finally found answer.
findBy and Example Executor doesn't work together.

通过设置子对象的过滤器并按示例执行器进行查询,如下所示。

public Page<Student> getStudentsPage(Student student, Pageable pageable) {
    logger.debug("Getting Students : {}, {}", student, pageable);
    // 从会话中获取学生的组织Id
    String organizationId = userService.getUserMe().getOrganization().getId(); 
    student.setOrganization(new Organization(organizationId));
    Page<Student> studentPage = studentRepository.findAll(Example.of(student), pageable);
    
    logger.debug("Students: {}", studentPage.getContent());
    return studentPage;
}

这按预期工作!!

谢谢!!

英文:

Finally found answer.
findBy and Example Executor doesn't work together.

By setting the child object filter and query by Example Executor as shown below.

public Page&lt;Student&gt; getStudentsPage(Student student, Pageable pageable) {
        logger.debug(&quot;Getting Students : {}, {}&quot;, student, pageable);
        //gets organization Id of the student from the session
        String organizationId = userService.getUserMe().getOrganization().getId(); 
        student.setOrganization(new Organization(organizationId));
        Page&lt;Student&gt; studentPage = studentRepository.findAll(Example.of(student), pageable);
        
        logger.debug(&quot;Students: {}&quot;, studentPage.getContent());
        return studentPage;
    }    

This works as expected!!

Thanks!!

huangapple
  • 本文由 发表于 2020年8月13日 13:46:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63388842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定