jackson - do not serialize lazy objects

后端 未结 4 1107
孤城傲影
孤城傲影 2020-12-03 05:55

I have an entity:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column
    private Stri         


        
4条回答
  •  忘掉有多难
    2020-12-03 06:44

    You can use Jackson's JSON Filter Feature:

    @Entity
    @JsonFilter("Book") 
    public class Book {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
    
        @Column
        private String title;
    
        @OneToMany(fetch = FetchType.LAZY, mappedBy = ("movie"),cascade = CascadeType.ALL)
        private List genre;
    } 
    
    @Entity
    @JsonFilter("Genre")
    public class Genre {
       ...
    }
    

    Then in the Controller you specify what to filter:

    @Controller
    public class BookController {
          @Autowired
          private ObjectMapper objectMapper;
    
          @Autowird
          private BookRepository bookRepository;
    
           @RequestMapping(value = "/book", method = RequestMethod.GET, produces =  "application/json")
           @ResponseBody
           public ResponseEntity getBooks() {
    
              final List books = booksRepository.findAll();
              final SimpleFilterProvider filter = new SimpleFilterProvider();
              filter.addFilter("Book", SimpleFilterProvider.serializeAllExcept("Genre");
              return new ResponseEntity<>(objectMapper.writer(filter).writeValueAsString(books), HttpStatus.OK)
           }
    
    }
    

    In this way, you can control when you want to filter the lazy relation at runtime

提交回复
热议问题