[Start Spring Boot] Dynamic / Static Filtering

·2024년 3월 21일
0

Start Spring Boot!

목록 보기
25/53
post-thumbnail

Filtering

Filtering이란?

  • Entity의 모든 정보를 반환하고 싶지 않을 수 있다.
  • Entity에서 반환할 정보만 필터링하는 것

반환이름을 변경하고 싶을 때

  • Entity
@JsonProperty("user_name")
private String name;
  • 다음과 같이 설정하면 name을 user_name으로 반환한다.

Static Filtering

  • 필터를 적용하면 모든 컨트롤러에서 적용됨
@JsonIgnore
private String name;

/////////////////////////////

@JsonIgnoreProperties({"name", "id"})
public class Team{
}
  • @JsonIgnore, @JsonIgnoreProperties()을 사용

Dynamic Filtering

  • 필터를 생성해서 함수마다 다르게 필터를 적용할 수 있음
  • Entity.java
@JsonFilter("TeamFilter")
public class SomeBean {
}
  • Controller.java
    @GetMapping("/{id}")
    public MappingJacksonValue getTeam(@PathVariable long id) {
        TeamDTO team = teamService.getTeamById(id);
        if(team == null) {
            throw new TeamNotFoundException("Team not found with id: " + id);
        }

        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(team);
        SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("name", "city");
        FilterProvider filters = new SimpleFilterProvider().addFilter("TeamFilter", filter);
        mappingJacksonValue.setFilters(filters);


        return mappingJacksonValue;
    }
    
  • MappingJacksonValue을 이용해서 반환한다.
  • SimpleBeanPropertyFilter을 이용해서 필터를 만들어서 적용하고 반환한다.
  • 모든 반환에 필터를 적용해야 정상적으로 작동함!

with HATEOAS

  • Controller.java
    @GetMapping("")
    public MappingJacksonValue getAllTeams() {
        List<TeamDTO> teams = teamService.getAllTeams();
        if(teams.isEmpty()) {
            throw new TeamNotFoundException("No teams found");
        }

        List<EntityModel<TeamDTO>> teamEntityModels = teams.stream()
                .map(team -> EntityModel.of(team,
                        linkTo(methodOn(TeamController.class).getTeam(team.getId())).withSelfRel(),
                        linkTo(methodOn(TeamController.class).getAllTeams()).withRel("teams"),
                        linkTo(methodOn(TeamController.class).deleteTeam(team.getId())).withRel("delete"),
                        linkTo(methodOn(TeamController.class).updateTeam(team.getId(), team)).withRel("update"))
                )
                .toList();

        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(CollectionModel.of(teamEntityModels,
                linkTo(methodOn(TeamController.class).getAllTeams()).withSelfRel()));
        SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("name", "city");
        FilterProvider filters = new SimpleFilterProvider().addFilter("TeamFilter", filter);
        mappingJacksonValue.setFilters(filters);

        return mappingJacksonValue;
    }
    
  • MappingJacksonValue을 반환한다.
  • MappingJacksonValue에 객체를 CollectionModel을 넣고 필터를 적용한다.


다음과 같다면 잘따라온 것 이다.

profile
백엔드 개발자가 꿈인 컴공과

0개의 댓글

관련 채용 정보