The way how to solve the issue related with Infinite Recursive fetching of data from relationships between Entity classes (Spring Boot JPA Hibernate)
-
This article is all about how to avoid recursive fetching of data from relationships designed in Database. I’ll explain everything with an example so that you will all understand clearly. Here I’m working with Intellij IDEA and MySQL databases.
1.1 Brief about the tables and the relationship used
Here in my example, I have created two Entity classes and they are connected with a OnetoMany relationship.
One student can have more than one email and this is the scenario taken. StudentId in ContactModel refers to the id field in StudentModel and This is a OnetoMany relationship. StudentModel is the “One” side and ContactModel is the “Many” side.
1.2 The classes before resolving the error
How the Entity classes are designed in Spring boot is given below in images.
StudentModel.java
ContactModel.java
1.3 Issue looks like this
Some data is included in the database and I have run some queries to fetch the data from the contact table.This is how it appears after fetching data,
This is an infinite recursion. This is the issue after designing the entity classes as above.
1.4 How to solve
There are many annotations such as @JsonManagedReference, @JsonBackReference, @JsonIgnore etc, to avoid this infinite recursion.But, when used them creates some errors in fetching and inserting data from and to the entities.
After searching a lot in internet and trying a lot, I came across the best way to solve this. It’s very simple.I used only to one annotation in the “One” side of the relationship.
@JsonIgnorePropertiesThis annotation ignores the fields from Jsonification. You need to use this in class level as below,
Actually when fetching data from StudentModel, you don’t need to fetch data from the field “contact”. So, I have asked to ignore that field . This annotation take the ignoring fields in a String array.So you need to give the field-names in an String array as above.
[ Note: You need to ignore two more fields, hibernateLazyInitializer, handler, otherwise it gives an error message like this when fetching data
“No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]>com.project.inventoryManagement.Models.ContactModel[\”student\”>com.project.inventoryManagement.Models.StudentModel$HibernateProxy$bYhYXmwK[\”hi bernateLazyInitializer\”])"
]
Happy Coding without bugs!
Thank you. -
Thanks bro, keep post these kind of articles.
-
Thanks good article , Happy coding
-
Nice artical Bro
-
Hi Udith..nice write up bro..
-
thanks, good article