在Spring Rest HATEOAS控制器中动态过滤字段

时间:2018-07-11 18:24:12

标签: java spring hibernate jpa jackson

我正在尝试弄清楚如何利用

SimpleBeanPropertyFilter.filterOutAllExcept());

带有spring生成的REST端点。

我有一个用户实体/模型。

    @Entity
    @JsonFilter("UserEntity")
    @Table(name = "user")
    public class UserEntity {
        private Integer id;
        private String firstName;
        private String lastName; 

        @Id
        @Column(name = "id", nullable = false)
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        @Basic
        @Column(name = "firstName", nullable = false)
        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        @Basic
        @Column(name = "lastName", nullable = false)
        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        } 

    }

还具有一个存储库类,该类可自动生成端点,例如/users/users/<id>。正是我想要的。

      @RepositoryRestResource(collectionResourceRel = "users", path = "users")
    public interface UserEntityRepository extends PagingAndSortingRepository<UserEntity, Integer> {

    }

最后,我有一个控制器。

    @RepositoryRestController 
    public class UserController {

        @Autowired
        UserEntityRepository userRepo;

        /*
        I am hoping that I can overwrite the automatically generated /stores endpoint only when the ?fields= attribute exists.

        @RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public MappingJacksonValue findAll(@RequestParam MultiValueMap<String, String> fields) { 
            Pageable pageable = new PageRequest(0, 20);

            Page<UserEntity> users = userRepo.findAll(pageable);

            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(stores);

            FilterProvider filters = new SimpleFilterProvider().addFilter("UserEntity", SimpleBeanPropertyFilter.filterOutAllExcept(fields));
            mappingJacksonValue.setFilters(filters);

            return mappingJacksonValue;
        }
        */
    }

如何钩住

的示例
SimpleBeanPropertyFilter.filterOutAllExcept()

进入默认的findAll()调用,而不会收到错误:

Circular view path [users]: would dispatch back to the current handler URL [/users] again. Check your ViewResolver setup!

我是spring / java的新手,所以例子很棒。

0 个答案:

没有答案