多对多关系查询

时间:2020-01-14 12:40:19

标签: java spring hibernate rest jpa

我有两个实体,Project和Tag具有多对多关系,我需要找到:

@Entity
public class Project implements Serializable {

    private Long id;
    private String name;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "project_tag",
           joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),
           inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id"))
    private Set<Tag> tags = new HashSet<>();
}

和:

public class Tag implements Serializable {
    private Long id;
    private String name;
}

因此,当标记来自某种形式时,我需要编写一个api来检索项目列表,它们带有 searchParam

@GetMapping("/projects")
public ResponseEntity<List<Project>> getAllProjects(Pageable pageable,
                                                                 @RequestParam String filter,
                                                                 @RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder,
                                                                 @RequestParam(required = false, defaultValue = "false") boolean eagerload) {

    Map<String, Object> searchParams = new HashMap<>();

    if(filter != null) {
        JsonParser parser = new BasicJsonParser();
        searchParams = parser.parseMap(filter);
    }

    final Page<ProjectShortDTO> page = projectService.getAllProjects(pageable, searchParams);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);

}

所以问题是我真的不知道该在服务方法中做什么:

@Transactional(readOnly = true)
public Page<ProjectDTO> getAllProjects(Pageable pageable, Map<String, Object> searchParams) {

    Specification<PetroleumApplication> where = parseFilter(searchParams, null);

    return projectRepository.findAll(pageable).map(ProjectDTO::new);
}

我尝试使用Spring规范,但我不知道如果要出现标签数组该怎么办,这种情况下如何使用规范api

0 个答案:

没有答案