【问题标题】:Alternative of JsonView in Spring DataSpring Data 中 JsonView 的替代方案
【发布时间】:2018-07-02 09:59:53
【问题描述】:

@JsonView 帮助我动态过滤掉输出数据中的某些字段。但在它过滤掉所有查询之前已经执行了。

我想在从数据库中查询字段之前忽略这些字段,以避免对关联表进行不必要的查询。(@JsonIgnore 以这种方式工作。但它不是动态的)。请帮帮我

【问题讨论】:

标签: spring spring-boot spring-data-jpa spring-data


【解决方案1】:

对于动态过滤,您可以使用我为 jackson 编写的一个小插件:

https://github.com/Antibrumm/jackson-antpathfilter

这应该在发出相关表查询之前启动。

【讨论】:

    【解决方案2】:

    在不减少数据库查询负载的情况下,我用来替代 JsonView 仅用作 API 返回的数据过滤器的某些情况的替代方法是使用投影和弹簧数据有很好的支持,这里有一个例子:

    使用 JsonView

    @Data
    @Entity
    public class Person {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @JsonView(View.NamesOnly.class)
        private String firstName;
    
        @JsonView(View.NamesOnly.class)
        private String lastName;
    }
    
    @GetMapping("/{id}")
    @JsonView(View.NamesOnly.class)
    public ResponseEntity<Person> findById(@PathVariable Long id) {
        return personRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    

    使用投影

    public interface NamesOnly {
    
        String getFirstName();
    
        String getLastName();
    }
    
    @Repository
    public interface PersonRepository extends JpaRepository<Person, Long> {
    
       @Query(" select p from Person p where p.id = :id")
       Optional<NamesOnly> findByIdNames(Long id);
    }
    
    @GetMapping(value = "/{id}", params = "projection")
    public ResponseEntity<NamesOnly> findByIdNames(@PathVariable Long id) {
        return personRepository.findByIdNames(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    

    这是一个完整的例子:https://github.com/pedrobacchini/spring-data-projection

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 2022-06-21
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多