Spring Boot: Include Transient fields in Jackson Serialization
If this is your first foray into Spring Boot with Hibernate, you may notice that you are not getting all the properties serialized from your POJOs. Specifically, fields with Hibernate’s `@Transient` annotation are ignored during serialization.
So what is going on here? We want our Hibernate to ignore the fields, but not Jackson! To make Jackson serialize those fields, we have to do a few things:
- Add necessary JSON annotations to the POJO fields
- Add an ObjectMapper bean to the application
Adding JSON Annotations
You may have Transient annotations on both your fields and their getters, but you only need to define a single annotation, `@JsonGetter`, on your field getter:
With the expected output of
{
"id": "...",
"transientProperty": "SomethingToInclude"
}
But, we’re not there yet. If you test your endpoint after adding these fields, you’ll notice the transient fields still do not show up.
Add ObjectMapper for Hibernate 5
Transient fields won’t show up yet because Jackson is still treating them as ignored fields for serialization.
For the next step, open up your Application.java file, and add the following bean. You may need to include dependencies, specifically jackson-datatype-hibernate#. You can use 3,4, or version 5 here. For the example, I will use jackson-datatype-hibernate5.
That’s it!
Start up your Spring application and test the endpoint. You should now see the transient fields with the JsonGetter annotation show up in your endpoint response.
To see code examples, click here.
Dependencies Used
- jackson-datatype-hibernate5@2.9.5
- jackson-databind@2.9.5
- jackson-annotations@2.9.5
- spring-boot-starter@2.0.1.RELEASE
- spring-boot-starter-web@2.0.1.RELEASE
- spring-boot-starter-data-jpa@2.0.1.RELEASE
Problems with this Solution
This doesn’t work when your entity implements an interface with the Transient annotation on the getter. I haven’t found a way to get around this yet.