Navigating Synthetic Field Issues in Spring Boot: A Troubleshooting Journey 😵💫🤯
😵💫 In this article I am going to share one of unexpected behaviour found with synthetic field with override equals
method.
In Spring Boot applications, entities are the backbone of data persistence, often managed through JPA and Hibernate. When dealing with complex business logic, it is common to introduce synthetic or transient fields, those not persisted in the database but essential for internal calculations or application-specific requirements.
✍️ If your Spring Boot application uses XML-based configuration for entity mappings, you can define synthetic fields in the model.xml
.
...
...
<literal name="syntheticField" synthetic="true" length="256">
<documentation> Define a synthetic field </documentation>
</literal>
...
...
👉As a programming practice, overriding the equals method is essential for proper comparison. I had the problem during that phase 😵💫.
When I use hibernate session flush, this equals
method overriding creates unwanted things. When we go deep into the session flush method, you can see in some points it checks dirty, using “isDirty()
” method in hibernate. When we use a synthetic field, it always return “false” when check with overrided equals
method. Then hibernate tries to create and delete data from database due to this confusion.
🤓👉 The conclusion reached for this problem was that the synthetic field is a field that is derived from other fields. So there is no need to worry about using the equals
method for generated values.