Spring MVC - JSON infinite recursion - json

I have bi-directional relationship like this...
Person.java
public class Person{
#JsonIgnore
#OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL,
fetch=FetchType.EAGER, mappedBy="person")
private Set<PeopleOrg> organization;
.....
}
PersonOrganization.java
public class PersonOrganization{
#JsonIgnore
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PERSONID", nullable=false)
private Person person;
}
Even with #JsonIgnore annotation I am getting infinite recursion error when trying to retrieve Person records. I have tried new annotations in 1.6 version. #JsonBackReference and #JsonManagedReference. Even then I am getting infinite recursion..
With #JsonBackReference("person-organization") on Person and #JsonManagedReference("person-organization") on PersonOrganization
org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]->com.entity.PersonOrganization["person"]->com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]...
Even If I interchange the annotations, I am still getting this exception.. Please let me know if there is something wrong with the mappings or the way I am using JSON annotations. Thanks

I've run into this before. But after moving #JsonIgnore from private field to getter of the field, infinite recursion is gone. So my wild guess is that #JsonIgnore might no work on private field. However, javadoc or tutorial of Jackson Java JSON-processor do not mention about this, so I cannot be 100% sure. Just for your information.

The following link says you should annotate the method used by JSON tool to traverse the object graph, to instruct the it to ignore the traversal.
http://jackson.codehaus.org/1.0.1/javadoc/org/codehaus/jackson/annotate/JsonIgnore.html
In my case I have two objects related like this Product <-> ProductImage. So JSON parser went into an infinite loop with out #JsonIgnore annotation on the following to get methods
#JsonIgnore
public Product getImageOfProduct() {
return imageOfProduct;
}
in ProductImage and
#JsonIgnore
public Set<ProductImage> getProductImages() {
return productImages;
}
in Product.
With the annotation, things are working fine.

I know this question isn't specifically about Spring Data REST, but I ran into this exception in the context of Spring Data REST, and wanted to share what the problem was. I had a bidirectional relationship involving an entity with no repository. Creating the repository made the loop disappear.

Since Jackson 1.6 you can use two annotations to solve the infinite recursion problem without ignoring the getters/setters during serialization: #JsonManagedReference and #JsonBackReference.
For more details refer https://stackoverflow.com/a/18288939/286588

Apparently since Jackson 1.6 you can use #JsonManagedReference and #JsonBackReference to effectively solve the infinite recursion problem.
I won't go into the details but this changing you classes to the below format should solve the problem.
public class Person{
#OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="person")
#Column(nullable = true)
#JsonManagedReference
private Set<PeopleOrg> organization;
.....
}
public class PersonOrganization{
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name="PERSONID")
#JsonBackReference
private Person person;
}
Basically Jackson converts Set<PeopleOrg> organization, the forward part of the reference a to json-like format using the marshalling process, it then looks for Person person, the back part of the reference and does not serialize it.
Credits - Kurt Bourbaki & More info - http://keenformatics.blogspot.co.ke/2013/08/how-to-solve-json-infinite-recursion.html

If A has B & B has A.
This is one to one relationship, but forming a circular relation.
In any of the class, use JustIgnore annotation.
class A
{
B b;
}
class B
{
#JsonIgnore
A a;
}
This applies for other relationships also like one to many.

This might be little old but you can add #JsonIgnore at class level with all properties it should ignore. e.g
#JsonIgnore("productImaes","...")
public class Product{ ...
}

Sometimes the member field may have inner reference to the same class type of itself, which could cause infinite recursion when toJson.
E.g.: you have a member field Klass a, while the class definition of that Klass is as below.
class Klass {
Klass mySibling;
public toString() {
return "something" + mySibling.whateverMethod;
}
}
Solution: refactor the member field, eliminate the inner reference.

This exception is because, your constructor field are not proper, please check your constructors properties once again in your classes, and check mapping give properly or not,
Keep the two Constructors, first is zero construction and second constructor is with fields and both should be contain the super

for me, i have tried #JsonIgnore, #JsonManagedReference/#JsonBackReference but nothing worked, till i read this Exception thrown ["hibernateLazyInitializer"] solution 1 and this Exception thrown ["hibernateLazyInitializer"] solution 2
solution 1 is to change from fetch.LAZY to fetch.EAGER, and solution 2 is using #JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}), and of course use #JsonIgnore in both solutions

Jackson works on Reflection by calling getters. I too had such a situation where I had a getter of the same Object inside its class. Jackson went into infinite recursion eating up stack by repeatedly calling its own getter. Removed getter, then it got fixed.
My Advice :
If you want to use jackson for conversion of an object, never keep getters which references the same object, like in case of singletons.

Related

Error thrown: "No serializer found for class java.lang.Long..." from controller while serializing JPA entity containing lazy "many-to-one" property

I am on Spring Boot 2.0.6, where an entity pet do have a Lazy many-to-one relationship to another entity owner
Pet entity
#Entity
#Table(name = "pets")
public class Pet extends AbstractPersistable<Long> {
#NonNull
private String name;
private String birthday;
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
#JsonIdentityReference(alwaysAsId=true)
#JsonProperty("ownerId")
#ManyToOne(fetch=FetchType.LAZY)
private Owner owner;
But while submitting a request like /pets through a client(eg: PostMan), the controller.get() method run into an exception as is given below:-
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Long and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.petowner.entity.Pet["ownerId"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.9.7.jar:2.9.7]
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191) ~[jackson-databind-2.9.7.jar:2.9.7]
Controller.get implementation
#GetMapping("/pets")
public #ResponseBody List<Pet> get() {
List<Pet> pets = petRepository.findAll();
return pets;
}
My observations
Tried to invoke explicitly the getters within owner through pet to force the lazy-loading from the javaassist proxy object of owner within the pet. But did not work.
#GetMapping("/pets")
public #ResponseBody List<Pet> get() {
List<Pet> pets = petRepository.findAll();
pets.forEach( pet -> pet.getOwner().getId());
return pets;
}
Tried as suggested by this stackoverflow answer at https://stackoverflow.com/a/51129212/5107365 to have controller call to delegate to a service bean within the transaction scope to force lazy-loading. But that did not work too.
#Service
#Transactional(readOnly = true)
public class PetServiceImpl implements PetService {
#Autowired
private PetRepository petRepository;
#Override
public List<Pet> loadPets() {
List<Pet> pets = petRepository.findAll();
pets.forEach(pet -> pet.getOwner().getId());
return pets;
}
}
It works when Service/Controller returning a DTO created out from the entity. Obviously, the reason is JSON serializer get to work with a POJO instead of an ORM entity without any mock objects in it.
Changing the entity fetch mode to FetchType.EAGER would solve the problem, but I did not want to change it.
I am curious to know why it is thrown the exception in case of (1) and (2). Those should have forced the explicit loading of lazy objects.
Probably the answer might be connected to the life and scope of that javassist objects got created to maintain the lazy objects. Yet, wondering how would Jackson serializer not find a serializer for a java wrapper type like java.lang.Long. Please do rememeber here that the exception thrown did indicate that Jackson serializer got access to owner.getId as it recognised the type of the property ownerId as java.lang.Long.
Any clues would be highly appreciated.
Edit
The edited part from the accepted answer explains the causes. Suggestion to use a custom serializer is very useful one in case if I don't need to go in DTO's path.
I did a bit of scanning through the Jackson sources to dig down to the root causes. Thought to share that too.
Jackson caches most of the serialization metadata on first use. Logic related to the use case in discussion starts at this method com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(Collection<?> value, JsonGenerator g, SerializerProvider provider). And, the respective code snippet is:-
The statement serializer = _findAndAddDynamic(serializers, cc, provider) at Line #140 trigger the flow to assign serializers for pet-level properties while skipping ownerId to be later processed through serializer.serializeWithType at line #147.
Assigning of serializers is done at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.resolve(SerializerProvider provider) method. The respective snippet is shown below:-
Serializers are assigned at line #340 only for those properties which are confirmed as final through the check at line #333.
When owner comes here, its proxied properties are found to be of type com.fasterxml.jackson.databind.type.SimpleType. Had this associated entity been loaded eagerly, the proxied properties obviously won't be there. Instead, original properties would be found with the values that are typed with final classes like Long, String, etc. (just like the pet properties).
Wondering why can't Jackson address this from their end by using the getter's type instead of using that of the proxied property. Anyway, that could be a different topic to discuss :-)
This has to do with the way that Hibernate (internally what spring boot uses for JPA by default) hydrates objects. A lazy object is not loaded until some parameter of the object is requested. Hibernate returns a proxy which delegates to the dto after firing queries to hydrate the objects.
In your scenario, loading OwnerId does not help because it is the key via which you are referencing the owner object i.e. the OwnerId is already present in the Pet object, so the hydration will not take place.
In both 1 and 2, you have not actually loaded the owner object, so when Jackson tries to serialize it at the controller level it fails. In 3 and 4, the owner object has been loaded explicitly, which is why Jackson does not run into any issues.
If you want 2 to work then load some parameter of owner, other than id, and hibernate will hydrate the object, and then jackson will be able to serialize it.
Edited Answer
The problem here is with the default Jackson serializer. This inspects the class returned and fetches the value of each attribute via reflection. In the case of hibernate entities, the object returned is a delegator proxy class in which all parameters are null, but all getters are redirected to the contained instance. When the object is inspected, the values of each attribute are still null, which is defaulted to an error as explained here
So basically, you need to tell jackson how to serialize this object. You can do so by creating a serializer class
public class OwnerSerializer extends StdSerializer<Owner> {
public OwnerSerializer() {
this(null);
}
public OwnerSerializer(Class<Owner> t) {
super(t);
}
#Override
public void serialize(Owner value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.getId());
jgen.writeStringField("firstName", value.getFirstName());
jgen.writeStringField("lastName", value.getLastName());
jgen.writeEndObject();
}
}
And setting it as the default serializer for the object
#JsonSerialize(using = OwnerSerializer.class)
public class Owner extends AbstractPersistable<Long> {
Alternatively, you can create a new Object of type Owner from the proxy class, manually populate it and set it in the response.
It is a little roundabout, but as a general practice you should not expose your DTO's externally anyway. The controller/domain should be decoupled from the storage layer.

JAX-RS cyclic JSON parsing

I know that there are already some topics discussing this problem, but I haven't find the most suitable solution for me.
To simplify my question, I have two entity, A and B:
public class A{
#LazyColletion(LazyCollectionOption.FALSE)
#ManyToMany(mappedBy="aSet")
private Set<B> bSet;
}
public class B{
#LazyColletion(LazyCollectionOption.FALSE)
#ManyToMany
private Set<A> aSet;
}
Sometimes I have to send the A class with the set of B and sometimes I have to do the reverse. I know that there are the #JsonIgnore and #JsonBackReference annotations, that prevent the cyclic reference and the StackOverflowError, for example:
public class A{
#LazyColletion(LazyCollectionOption.FALSE)
#ManyToMany(mappedBy="aSet")
private Set<B> bSet;
}
public class B{
#JsonIgnore
#LazyColletion(LazyCollectionOption.FALSE)
#ManyToMany
private Set<A> aSet;
}
This code works ok, when I send the A class with the set of B, but when I have to do the reverse, the B class does not contain the set of A, because of the #JsonIgnore annotation. Are there any possibilities to solve this issue?
And I have a second question related to this: When I lazily initialize a collection and JAX-RS parsea it to JSON, I got a LazyInitializationException. It is ok, but can I set somehow if this is the case, the JSON parser only set null to this collection in the JSON object?

Spring Data Rest Ambiguous Association Exception

The newly added LinkCollectingAssociationHandler is throwing a MappingException due to an ambiguous association in my domain class.
The links array looks like this:
[<http://localhost:8080/rooms/2/roomGroups>;rel="roomGroups", <http://localhost:8080/rooms/2/userGroup>;rel="userGroup", <http://localhost:8080/rooms/2/room>;rel="room", <http://localhost:8080/rooms/2/originatingConferences>;rel="originatingConferences", <http://localhost:8080/rooms/2/user>;rel="user"]
And it is trying to add another 'room' relation when it throws the exception.
The issue is that it seems to be adding links to relations which I have explicitly marked with #RestResource(exported = false)
Here is an example of a relation which I believe is causing this issue:
#JsonIgnore
#RestResource(exported = false)
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.room", cascade = {CascadeType.REMOVE})
private Set<RoomsByUserAccessView> usersThatCanDisplay = new HashSet<>();
The type RoomsByUserAccessView has an embedded id made up of a Room and a User.
I have also annotated the embedded id property with:
#JsonIgnore
#RestResource(exported = false)
private RoomsByUserAccessViewId pk = new RoomsByUserAccessViewId();
and its properties like this:
#JsonIgnore
#RestResource(exported = false)
private Room room;
#JsonIgnore
#RestResource(exported = false)
private User userWithAccess;
public RoomsByUserAccessViewId() {
//
}
How can I get it to ignore these relations properly when serializing to JSON?
My code was working prior to DATAREST-262 (https://github.com/spring-projects/spring-data-rest/commit/1d53e84cae3d09b09c4b5a9a4caf438701527550)
The full error message returned when I try to visit the rooms/ endpoint is as follows:
{
timestamp: "2014-03-17T13:38:05.481-0500"
error: "Internal Server Error"
status: 500
exception: "org.springframework.http.converter.HttpMessageNotWritableException"
message: "Could not write JSON: Detected multiple association links with same relation type! Disambiguate association #com.fasterxml.jackson.annotation.JsonIgnore(value=true) #javax.persistence.ManyToOne(fetch=EAGER, cascade=[], optional=true, targetEntity=void) #org.springframework.data.rest.core.annotation.RestResource(description=#org.springframework.data.rest.core.annotation.Description(value=), path=, exported=false, rel=) private com.renovo.schedulerapi.domain.Room com.renovo.schedulerapi.domain.RoomsByUserAccessViewId.room using #RestResource! (through reference chain: org.springframework.hateoas.PagedResources["content"]->java.util.UnmodifiableCollection[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Detected multiple association links with same relation type! Disambiguate association #com.fasterxml.jackson.annotation.JsonIgnore(value=true) #javax.persistence.ManyToOne(fetch=EAGER, cascade=[], optional=true, targetEntity=void) #org.springframework.data.rest.core.annotation.RestResource(description=#org.springframework.data.rest.core.annotation.Description(value=), path=, exported=false, rel=) private com.renovo.schedulerapi.domain.Room com.renovo.schedulerapi.domain.RoomsByUserAccessViewId.room using #RestResource! (through reference chain: org.springframework.hateoas.PagedResources["content"]->java.util.UnmodifiableCollection[0])"
}
I had a very similar problem . When adding a bidirectional relationship between two entities
I got an exception ""Could not write JSON: Detected multiple association links with same
relation type!" , While trying some solutions that i found here
(#JsonIgnore, #JsonIdentity, #RestResource, I also tried to do what Oliver offered
)
(The relation was properly defined with #JsonManagedReference and #JsonBackReference)
Nothing helped.
At the end i managed to understand that spring data rest is trying to
figure out if the related entity is linkable ( while trying to build the json of the
requested entity )
(LinkCollectingAssociationHandler : doWithAssociation -> isLinkableAssociation)
, For doing that he is looking for a repository that deals with the
related entity. After adding a repository for the related entity.. works like a charm..
(I suppose that after adding a repo a mapping RepositoryAwareResourceInformation is being
created for this entity (that is what I saw at debug).
I had this issue, and solved it as Ron suggests, but I thought I would expound a little. I didn't fully understand the first couple times I read Ron's answer...
#NodeEntity
public class Player extends Entity
#NodeEntity
public class PlayerTrade extends Entity
#NodeEntity
public class Trade extends Entity
I had repositories for Player and Trade, but none for PlayerTrade:
#RepositoryRestResource
public interface PlayerRepository extends GraphRepository<Player> {
#RepositoryRestResource
public interface TradeRepository extends GraphRepository<Trade> {
As soon as I added the last repo it worked.
#RepositoryRestResource
public interface PlayerTradeRepository extends GraphRepository<PlayerTrade>
I tried using #RestResource with rel or excluded, but couldn't get it dialed in. Does this mean that every entity in our JSON graph must have a repository?

Serializing JPA entities to JSON using Jackson

Question regarding combination of Jackson/JPA
If there are about 20 entities in current application and I have add Jackson dependency in POM, does it mean all entities are by default ready to convert to JSON object? I saw a sample project seems only class annotated as #JsonIgnored is skipped by JSON. If so, then how can this happen, what is behind such mechanism? how JACKSON handle those entities which don't have any Jackson annotation, by default ignored or not? I've been looking for resources online but not much luck.
If only one of the 20 entities need to be mapped to JSON object, does it mean I have to add #JsonIgnore to all other 19 entities? If not, how Jackson differentiate with entity to work on?
Thanks.
Jackson and JPA don't have anything to do with each other. Jackson is a JSON parsing library and JPA is a persistence framework. Jackson can serialize almost any object - the only requirement being that the object have some kind of recognizable properties (Javabean type properties, or bare fields annotated with #JsonProperty. There is an additional requirement for deserialization, that the target type have a default (no-arg) constructor. So, for example, this is an object that Jackson can serialize:
// Class with a single Javabean property, "name"
class Person {
private String name;
public String getName() { return name ; }
public String setName(String name) { this.name = name ; }
}
And here is another:
// Class with a single field annotated with #JsonProperty
class Account {
#JsonProperty("accountNumber")
private String accountNumber;
}
And here is yet another:
#Entity
public class User {
#Id
private Long id;
#Basic
private String userName;
#Basic
#JsonIgnore
private String password;
#Basic
#JsonIgnore
private Address address;
// Constructors, getters, setters
}
The last example shows a JPA entity class - as far as Jackson is concerned it can be serialized just like any other type. But, take note of its fields: when this object is serialized into JSON two of the fields will not be included - 'password' and 'address'. This is because they have been annotated with #JsonIgnore. The #JsonIgnore annotation allows a developer to say 'Hey, its ok to serialize this object, but when you do so don't include these fields in the output'. This exclusion only occurs for the fields of this object, so for example, if you included an Address field in another class, but did not mark the field as ignorable, it would be serialized.
To prevent serialization of a type in all cases, regardless of context, use the #JsonIgnoreType annotation. When used on a type it basically means 'I dont care where this type is used, never serialize it'.
No, you don't need to add #JsonIgnore on every class and if you had tried you would have gotten a compile error, since you can't put it there. Jackson will only work on objects you give to it, it's no magic.
The Jackson documentation is easily found online, such at its project page on github or on the codehaus website.

Lazy Loadng error in JSON serializer

I have such kind of #OneToOne Hibernate relationShip
public class Address implements Serializable {
private String id;
private String city;
private String country;
//setter getters ommitted
}
public class Student implements Serializable {
private String id;
private String firstName;
private String lastName;
private Address address;
}
address Item is mapped as LAZY.
Now I want to fetch user and it's address using
session.load(Student.class,id);
In my daoService.
Then I return it as JSON from my Spring MVC controller:
#RequestMapping(value="/getStudent.do",method=RequestMethod.POST)
#ResponseBody
public Student getStudent(#RequestParam("studentId") String id){
Student student = daoService.getStudent(id);
return student;
}
Unfortunately, it's not working because of Lazy clasees and I fails with:
org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.vanilla.objects.Student_$$_javassist_1["address"]->com.vanilla.objects.Address_$$_javassist_0["handler"])
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
I do use OpenSessionInViewInterceptor and it works just fine.
I understand that I can user left join HQL query and retrieve student and address that way and solve the problem. I also understand that changing relation to EAGER will solve it.
But how can I serialize to JSON lazy classes using standard jackson message converter which of cause I added to my XML file.
The easiest solution: Don't serialize entities, use Value Objects.
If that is not an option for you, make sure that the entity Object is detached.
With JPA (2), you would use EntityManager.detach(entity), with plain Hibernate the equivalent is Session.evict(entity).
Once I write a processor to handle this but now it's easy to fix this by using the jackson hibernate module.
Within your DAO method add Hibernate.initialize(<your getter method>); to resolve this.
Student student = findById(<yourId>);
Hibernate.initialize(student.getAddress());
...
return student;
Try like the above.
There is another option that solves your problems. You can add this filter in web.xml
<filter>
<filter-name>springOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The problem is that entities are loaded lazy and serialization happens before they get loaded fully.
But how can I serialize to JSON lazy classes using standard jackson
message converter which of cause I added to my XML file.
First of all, I don't advise to use DTO/Value Object only to solve this issue.
You may find it easy at the beginning but at each new development/change, the duplicate code means making twice modifications at each time... otherwise bugs.
I don't mean that VO or DTO are bad smells but you should use them for reasons they are designed (such as providing a content/structure that differs according to logical layers or solving an unsolvable serialization problem).
If you have a clean and efficient way to solve the serialization issue without VO/DTO and you don't need them, don't use them.
And about it, there is many ways to solve lazy loading issue as you use Jackson with Hibernate entities.
Actually, the simplest way is using FasterXML/jackson-datatype-hibernate
Project to build Jackson module (jar) to support JSON serialization
and deserialization of Hibernate (http://hibernate.org) specific
datatypes and properties; especially lazy-loading aspects.
It provides Hibernate3Module/Hibernate4Module/Hibernate5Module, extension modules that can be registered with ObjectMapper to provide a well-defined set of extensions related to Hibernate specificities.
To do it working, you just need to add the required dependency and to add the
Jackson Module available during processings where it is required.
If you use Hibernate 3 :
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate3</artifactId>
<version>${jackson.version.datatype}</version>
</dependency>
If you use Hibernate 4 :
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>${jackson.version.datatype}</version>
</dependency>
And so for...
Where jackson.version.datatype should be the same for the used Jackson version and the ackson-datatype extension.
If you use or may use Spring Boot, you just need to declare the module as a bean in a specific Configuration class or in the SpringBootApplication class and it will be automatically registered for any Jackson ObjectMapper created.
The 74.3 Customize the Jackson ObjectMapper Spring Boot section states that :
Any beans of type com.fasterxml.jackson.databind.Module will be
automatically registered with the auto-configured
Jackson2ObjectMapperBuilder and applied to any ObjectMapper instances
that it creates. This provides a global mechanism for contributing
custom modules when you add new features to your application.
For example :
#Configuration
public class MyJacksonConfig {
#Bean
public Module hibernate5Module() {
return new Hibernate5Module();
}
}
or :
#SpringBootApplication
public class AppConfig {
public static void main(String[] args) throws IOException {
SpringApplication.run(AppConfig.class, args);
}
#Bean
public Module hibernate5Module() {
return new Hibernate5Module();
}
}