21

What does this following piece of code do in Java Sprint Boot?

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
mattsmith5
  • 540
  • 4
  • 29
  • 67
  • Does this answer your question? [How to ignore "handler": {}, "hibernateLazyInitializer": {} in json jackson in Spring hibernate project?](https://stackoverflow.com/questions/41582979/how-to-ignore-handler-hibernatelazyinitializer-in-json-jackson-in-s) – crizzis May 02 '21 at 09:41

1 Answers1

43

When you have JPA / Hibernate Entities with @Entity annotation, and when you fetch data from the database using a repository or using getMethod() from the parent entity for the field which is being lazy-loaded from the parent entity, hibernate returns an object which will have all the fields/properties of the class which are mapped to DB table. On top of these fields, this object will also have two extra fields which are hibernateLazyInitializer and handler that is used to lazily load an entity.

If you have any use case of serializing this entity in JSON String format using Jackson library directly or indirectly (Maybe if you're returning entity as it to any REST API response or if you're storing entity to JSON data store like Elasticsearch), the JPA entity will be serialized with all the fields and hibernateLazyInitializer and handler as extra fields. So, if you do not ignore these fields, they will be serialized in JSON format which you can see if you read the JSON string.

So, to avoid this unnecessary serialization, you have to write this piece of code on JPA / Hibernate entity which will tell Jackson library that "Serialized JSON should not have fields hibernateLazyInitializer and handler. If you find them in object, just ignore them":

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
Vicky Ajmera
  • 681
  • 6
  • 8
  • 1
    Great explanation. I wonder why this wouldn't be default behavior for Jackson? – cbmeeks Jun 21 '22 at 22:15
  • Thanks, @cbmeeks. This can not be the default behaviour of Jackson as it's a generic library to deal with JSON. And the fields hibernateLazyInitializer and handler are the fields specific to hibernate. So, a generic library wouldn't have specific logic to handle the use cases of another library. – Vicky Ajmera Jun 23 '22 at 07:07
  • Is there a way to configure this globally? – Lukas Nov 13 '22 at 21:55