101

I have a simple controller that return a User object, this user have a attribute coordinates that have the hibernate property FetchType.LAZY.

When I try to get this user, I always have to load all the coordinates to get the user object, otherwise when Jackson try to serialize the User throws the exception:

com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session

This is due to Jackson is trying to fetch this unfetched object. Here are the objects:

public class User{

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    @JsonManagedReference("user-coordinate")
    private List<Coordinate> coordinates;
}

public class Coordinate {

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    @JsonBackReference("user-coordinate")
    private User user;
}

And the controller:

@RequestMapping(value = "/user/{username}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String username) {
        
    User user = userService.getUser(username);
        
    return user;
        
}

There is a way to tell Jackson to not serialize the unfetched objects? I've been looking other answers posted 3 years ago implementing jackson-hibernate-module. But probably it could be achieved with a new jackson feature.

My versions are:

  • Spring 3.2.5
  • Hibernate 4.1.7
  • Jackson 2.2
5
  • 4
    approach described in these 2 links worked for me, Spring 3.1, Hibernate 4 and Jackson-Module-Hibernate and FasterXML / jackson-datatype-hibernate
    – indybee
    Commented Feb 11, 2014 at 17:20
  • Thank you indybee, I've been watching the tutorial, spring 3.2.5 already have a MappingJackson2HttpMessageConverter, but I cannot use it to avoid the non fetched lazy object, also I've tried to implementing the one in the tutorial, but nothing...
    – r1ckr
    Commented Feb 13, 2014 at 14:05
  • 1
    are you getting the same error "could not initialize proxy" or something different? (i used the additional HibernateAwareObjectMapper described in the articles with Spring 3.2.6 and Hibernate 4.1.7 and jackson 2.3)
    – indybee
    Commented Feb 13, 2014 at 14:24
  • 1
    Got it!! Since version 3.1.2 Spring have his own MappingJackson2HttpMessageConverter and have almost the same behavior of the one in the tutorial, but the problem was that I am using Spring java config and I'm starting with javaconfigs. I was trying to make a @Bean MappingJackson2HttpMessageConverter, instead of adding it to the HttpMessageConverters of Spring, maybe it's clearer in the answer :)
    – r1ckr
    Commented Feb 13, 2014 at 16:49
  • Is it broken in Spring Boot 2? Commented Aug 11, 2018 at 2:32

17 Answers 17

106

I finally found the solution! thanks to indybee for giving me a clue.

The tutorial Spring 3.1, Hibernate 4 and Jackson-Module-Hibernate have a good solution for Spring 3.1 and earlier versions. But since version 3.1.2 Spring have his own MappingJackson2HttpMessageConverter with almost the same functionality as the one in the tutorial, so we don't need to create this custom HTTPMessageConverter.

With javaconfig we don't need to create a HibernateAwareObjectMapper too, we just need to add the Hibernate4Module to the default MappingJackson2HttpMessageConverter that Spring already have and add it to the HttpMessageConverters of the application, so we need to:

  1. Extend our spring config class from WebMvcConfigurerAdapter and override the method configureMessageConverters.

  2. On that method add the MappingJackson2HttpMessageConverter with the Hibernate4Module registered in a previus method.

Our config class should look like this:

@Configuration
@EnableWebMvc
public class MyConfigClass extends WebMvcConfigurerAdapter{

    //More configuration....

    /* Here we register the Hibernate4Module into an ObjectMapper, then set this custom-configured ObjectMapper
     * to the MessageConverter and return it to be added to the HttpMessageConverters of our application*/
    public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper mapper = new ObjectMapper();
        //Registering Hibernate4Module to support lazy objects
        mapper.registerModule(new Hibernate4Module());

        messageConverter.setObjectMapper(mapper);
        return messageConverter;

    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Here we add our custom-configured HttpMessageConverter
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
    }

    //More configuration....
}

If you have an xml configuration, you don't need to create your own MappingJackson2HttpMessageConverter either, but you do need to create the personalized mapper that appears in the tutorial (HibernateAwareObjectMapper), so your xml config should look like this:

<mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper">
            <bean class="com.pastelstudios.json.HibernateAwareObjectMapper" />
        </property>
    </bean>
</mvc:message-converters>

Hope this answer be understandable and helps someone find the solution for this problem, any questions feel free to ask!

11
  • 3
    Thanks for sharing the solution. However after a few tries, I found that the latest jackson at the moment (2.4.2) does NOT work with spring 4.0.6. I still have the "no session" error. Only when I down graded jackson version back to 2.3.4 (or 2.4.2), did it start working.
    – Robin
    Commented Sep 28, 2014 at 12:14
  • 1
    Thanks for pointing MappingJackson2HttpMessageConverter out! I was looking for a class like this for a while.
    – LanceP
    Commented May 8, 2015 at 18:09
  • 1
    Thank you very much! I have just tested it and its working with Spring 4.2.4, Jackson 2.7.1-1 and JacksonDatatype 2.7.1 :)
    – Isthar
    Commented Feb 17, 2016 at 14:01
  • 2
    This doesn't resolve the problem in Spring Data REST. Commented Jul 13, 2016 at 9:38
  • 1
    How to solve the same issue, if Springboot is used in place of Spring?. I have tried registering the Hibernate4 module(which is the version I have currently), but that did not solve my issue. Commented Sep 7, 2018 at 19:29
50

As of Spring 4.2 and using Spring Boot and javaconfig, registering the Hibernate4Module is now as simple as adding this to your configuration:

@Bean
public Module datatypeHibernateModule() {
  return new Hibernate4Module();
}

ref: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

8
  • 27
    For Hibernate 5 (as in the current version of Spring Boot), it is Hibernate5Module. It additionally needs a dependency to <groupId>com.fasterxml.jackson.datatype</groupId><artifactId>jackson-datatype-hibernate5</artifactId>
    – Zeemee
    Commented Jan 2, 2017 at 12:05
  • 1
    Worked for me as well on Spring Boot 2.1. Was beginning to drive me crazy.
    – Van Dame
    Commented Nov 26, 2018 at 12:03
  • It's not clear how to implement this. I get an incompatible types error.
    – aardbol
    Commented Dec 15, 2018 at 19:16
  • 2
    Awesome! Worked for me with Spring Boot 2.0.6 and Hibernate 5.
    – GarouDan
    Commented Jan 4, 2019 at 13:42
  • 1
    thanks @chrismarx, I'd give you 1337 upvotes for this answer if SO let me.
    – Johannes
    Commented Jan 11, 2022 at 1:22
15

This is similar to accepted solution by @rick.

If you don't want to touch existing message converters configuration you can just declare a Jackson2ObjectMapperBuilder bean like:

@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
    return new Jackson2ObjectMapperBuilder()
        .modulesToInstall(Hibernate4Module.class);
}

Do not forget to add the following dependency to your Gradle file (or Maven):

compile 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.4.4'

Useful if you have a application and you want to keep the ability to modify Jackson features from application.properties file.

4
  • How can we achieve this (Configuring Jackson to avoid lazy loaded object) using application.properties file?
    – hemu
    Commented May 15, 2016 at 5:51
  • 1
    That's not what is being said here. @Luis Belloch's solution suggests that you create the Jackson2ObjectMapperBuilder so that you don't override spring boots default message converter and continue to use the application.properties values to control jackson properties.
    – kapad
    Commented Mar 5, 2018 at 7:58
  • sorry... I am new where would you implement this method? With spring boot It uses Spring 5 which WebMvcConfigurerAdapter is deprecated
    – Eric Huang
    Commented May 28, 2018 at 16:34
  • Hibernate4Module is legacy Commented Apr 25, 2020 at 9:33
11

In the case of Spring Data Rest then, while the solution posted by @r1ckr works, all that is required is to add one of the following dependencies depending on your Hibernate version:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate4</artifactId>
    <version>${jackson.version}</version>
</dependency>

or

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>${jackson.version}</version>
</dependency>

Within Spring Data Rest there is a class:

org.springframework.data.rest.webmvc.json.Jackson2DatatypeHelper

which will auto-detect and register the Module on application start-up.

There is however an issue:

Issue Serializing Lazy @ManyToOne

2
  • How do you configure this with spring boot when you are not using Spring Data Rest?
    – Eric Huang
    Commented May 28, 2018 at 16:29
  • Not enough. You also need @Bean hibernate5Module() Commented Apr 25, 2020 at 9:32
7

I've spent whole day trying to solve the same problem. You can do it without changing existing message converters configuration.

In my opinion the easiest way to solve this problem only with 2 steps with help of jackson-datatype-hibernate:

kotlin example (same as java):

  1. Add In build.gradle.kts:
implementation("com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:$jacksonHibernate")
  1. Create @Bean
   @Bean
   fun hibernate5Module(): Module = Hibernate5Module()

  • Notice that Module is com.fasterxml.jackson.databind.Module, not java.util.Module

  • Also good practice is to add @JsonBackReference & @JsonManagedReference to @OneToMany & @ManyToOne relationships. @JsonBackReference could be only 1 in class.

5

The following solution is for Spring 4.3, (non-boot) & Hibernate 5.1 where we transitioned all fetchtypes to fetch=FetchType.LAZY from cases of fetch=FetchType.EAGER for performance reasons. Immediately we saw the com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy exception due to the lazy load issue.

First, we add the following maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
</dependency>  

Then the following is added to our Java MVC configuration file:

@Configuration
@EnableWebMvc 
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

    Hibernate5Module h5module = new Hibernate5Module();
    h5module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
    h5module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING);

    for (HttpMessageConverter<?> mc : converters){
        if (mc instanceof MappingJackson2HttpMessageConverter || mc instanceof MappingJackson2XmlHttpMessageConverter) {
            ((AbstractJackson2HttpMessageConverter) mc).getObjectMapper().registerModule(h5module);
        }
    }
    return;
}

Notes:

  • You need to create and configure the Hibernate5Module to get behavior similar to Jackson without this module. The default makes incompatible assumptions.

  • Our WebMvcConfigurerAdapter has a lot of other configuration in it and we wanted to avoid another configuration class, which is why we didn't use the WebMvcConfigurationSupport#addDefaultHttpMessageConverters function that has been referred to on other posts.

  • WebMvcConfigurerAdapter#configureMessageConverters disables all of Spring's internal configuration of message converters. We preferred to avoid the potential issues around this.

  • Using extendMessageConverters enabled access to all the automatically-configured Jackson classes without losing the configuration of all other message converters.

  • Using getObjectMapper#registerModule we were able to add the Hibernate5Module to the existing converters.

  • The module was added to both the JSON and XML processors

This addition solved the issue with Hibernate and lazy loading but caused a residual issue with the generated JSON format. As reported in this github issue, the hibernate-jackson lazy load module currently ignores the @JsonUnwrapped annotation, leading to potential data errors. This happens regardless of the force-loading feature setting. The problem has been there since 2016.


Note

It appears that by adding the following to classes that are lazy-loaded, the built-in ObjectMapper works without adding the hibernate5 module:

@JsonIgnoreProperties(  {"handler","hibernateLazyInitializer"} )
public class Anyclass {
1
  • The solution could be much more easier: kotlin @Bean fun hibernate5Module(): Module = Hibernate5Module() Commented Apr 25, 2020 at 9:29
4

If you use XML config and use <annotation-driven />, I found that you have to nest <message-converters> inside <annotation-driven> as recommended on the Jackson Github account.

Like so:

<annotation-driven>
  <message-converters>
    <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <beans:property name="objectMapper">
        <beans:bean class="com.pastelstudios.json.HibernateAwareObjectMapper" />
      </beans:property>
    </beans:bean> 
  </message-converters>
</annotation-driven>

`

1
3

For those who came here looking to find the solution for Apache CXF-based RESTful service, the configuration that fixes it is below:

<jaxrs:providers>
    <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider">
        <property name="mapper" ref="objectMapper"/>
    </bean>
</jaxrs:providers>

<bean id="objectMapper" class="path.to.your.HibernateAwareObjectMapper"/>

Where HibernateAwareObjectMapper is defined as:

public class HibernateAwareObjectMapper extends ObjectMapper {
    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate5Module());
    }
}

The following dependency is required as of June 2016 (provided you're using Hibernate5):

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>2.7.4</version>
</dependency>  
0
1
TLDR: Always serialize DTO's, avoid returning entities. Explicitly for OP question, answer is @JsonIgnore

The reason for the issue is that when retrieving lazily-loaded data, first step is populate the main object, and second to retrieve the data within its proxies. For this, an open Session in Hibernate is needed.

The problem arises when the second step happens after the transaction has closed, which leads to a LazyInitializationException.

I'm going to summarize some solutions here while adding mine:

1. Avoid entity serialization, **instead serialize a dto**
2. Add `@JsonIgnore` to your `LAZY` attributes
3. Change `FetchType` to `EAGER`
4. Set `hibernate.enable_lazy_load_no_trans=true` 

Only points 1 and 2 are recommended, the other 2 aren't meant to be used at serialization phase. As they have a HUGE performance cost there, they both make a hit to the database to retrieve extra data. Option 4, actually creates a new transaction for every lazy object so please AVOID!.

My grain of sand in this question is to highly recommend to explicitly use ONLY options 1 and 2, and also FetchType.EAGER only for business logic, not as a solution for this issue.

0

You can use the following helper from Spring Data Rest project:

Jackson2DatatypeHelper.configureObjectMapper(objectMapper);
1
0

I made a very simple solution to this problem.

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Set<Pendency> getPendencies() {
    return Hibernate.isInitialized(this.pendencies) ? Collections.unmodifiableSet(this.pendencies) : new HashSet<>();
}

In my case I was giving the error because whenever I was returning a pendencies, as a good practice I converted it to a list that cannot be modified, but how it could or might not be in lazy depending on the method I used to get instance (with or without fetch), I do a test before it was initialized by Hibernate and add the annotation that prevents serializing an empty property and that solved my problem.

1
  • But when you need the actual data based on that object instance and Hibernate is supposed to really lazy load the data, it will not do it because it is already initialized?!
    – d00d
    Commented Nov 8, 2022 at 10:31
0

We couldn’t work around the problem that we had to call Hibernate.initialize(objX.getAttributeY()) for all Attributes. So here we wrote a utils class to call the initialize methods on all attributes that have the Entity annotation. Collections still must be handled separately.

import org.hibernate.Hibernate;

import javax.persistence.Entity;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HibernateInitialiseUtil<T> {

    private final List<Method> entityGetterMethods;

    public HibernateInitialiseUtil(Class<T> clazz) {
        this.entityGetterMethods = this.getGettersMethodsOfEntityAttributes(clazz);
    }

    public void initializeAllEntityAttributes(T obj) throws InvocationTargetException, IllegalAccessException {
        for (Method getter : this.entityGetterMethods) {
            Hibernate.initialize(getter.invoke(obj));
        }
    }

    private List<String> getNameOfEntityAttributes(final Class<T> targetClass) {
        Field[] attributes =  targetClass.getDeclaredFields();
        List<String> fields = new ArrayList<>();
        for (Field attribute : attributes) {
            if (attribute.getType().isAnnotationPresent(Entity.class)) {
                fields.add(attribute.getName());
            }
        }
        return fields;
    }

    private List<Method> getGettersMethodsOfEntityAttributes(final Class<T> targetClass) {
        List<Method> resultList = new ArrayList<>();
        for (String attributeName : getNameOfEntityAttributes(targetClass)) {
            try {
                PropertyDescriptor pd = new PropertyDescriptor(attributeName, targetClass);
                Method getter = pd.getReadMethod();
                resultList.add(getter);
            } catch (IllegalArgumentException | IntrospectionException e) {
                e.printStackTrace();
            }
        }
        return Collections.unmodifiableList(resultList);
    }
}
0

There is a way to tell Jackson to not serialize the unfetched objects?

Yes, by using the @JsonSerialize annotation.

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Collection;
import org.hibernate.Hibernate;

// This custom serializer is to prevent Jackson from triggering a fetch for
// lazy-loaded fields, which is its default behavior.
public class HibernateInitializedCollectionSerializer extends JsonSerializer<Collection<?>> {

    @Override
    public void serialize(Collection<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (Hibernate.isInitialized(value)) {
            gen.writeObject(value);
        } else {
            // Write an empty array if the collection has not been initialized
            gen.writeStartArray();
            gen.writeEndArray();
        }
    }
}

Then on your User / Parent Entity

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
@ToString.Exclude
@EqualsAndHashCode.Exclude
@JsonSerialize(using = HibernateInitializedCollectionSerializer.class)
private Set<Coordinates> coordinates;
-1

Although this question is slightly different to this one : Strange Jackson exception being thrown when serializing Hibernate object, the underlying problem can be fixed in the same way with this code:

@Provider
public class MyJacksonJsonProvider extends JacksonJsonProvider {
    public MyJacksonJsonProvider() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        setMapper(mapper);
    }
}
0
-1

I tried this, and worked:

// custom configuration for lazy loading

public static class HibernateLazyInitializerSerializer extends JsonSerializer<JavassistLazyInitializer> {

    @Override
    public void serialize(JavassistLazyInitializer initializer, JsonGenerator jsonGenerator,
            SerializerProvider serializerProvider)
            throws IOException, JsonProcessingException {
        jsonGenerator.writeNull();
    }
}

and configure mapper:

    mapper = new JacksonMapper();
    SimpleModule simpleModule = new SimpleModule(
            "SimpleModule", new Version(1,0,0,null)
    );
    simpleModule.addSerializer(
            JavassistLazyInitializer.class,
            new HibernateLazyInitializerSerializer()
    );
    mapper.registerModule(simpleModule);
0
-1

I tried @rick's useful answer, but ran into the problem that "well-known modules" such as jackson-datatype-jsr310 weren't automatically registered despite them being on the classpath. (This blog post explains the auto-registration.)

Expanding on @rick's answer, here's a variation using Spring's Jackson2ObjectMapperBuilder to create the ObjectMapper. This auto-registers the "well-known modules" and sets certain features in addition to installing the Hibernate4Module.

@Configuration
@EnableWebMvc
public class MyWebConfig extends WebMvcConfigurerAdapter {

    // get a configured Hibernate4Module
    // here as an example with a disabled USE_TRANSIENT_ANNOTATION feature
    private Hibernate4Module hibernate4Module() {
        return new Hibernate4Module().disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
    }

    // create the ObjectMapper with Spring's Jackson2ObjectMapperBuilder
    // and passing the hibernate4Module to modulesToInstall()
    private MappingJackson2HttpMessageConverter jacksonMessageConverter(){
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                            .modulesToInstall(hibernate4Module());
        return new MappingJackson2HttpMessageConverter(builder.build());
  }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonMessageConverter());
        super.configureMessageConverters(converters);
    }
}
6
  • Do you have an update about this topic? I'm having the issue currently. Ofcourse whenI add the hibernate5Module (because im using hibernate 5), jackson ignores the proxy of non initialized objects, but it seems that the " well-known modules" are not being registered despite I useyour approach. I do know this, because some parts of my application are broken, and when I remove the Module, they work again. Commented Oct 7, 2018 at 17:55
  • @DanielHenao Have you studied spring.io/blog/2014/12/02/…? I switched to Hibernate5, using the DelegatingWebMvcConfiguration class (instead of WebMvcConfigurerAdapter) as suggested by the Jackson-Antpath-Filter: @Override public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) { messageConverters.add(jacksonMessageConverter()); addDefaultHttpMessageConverters(messageConverters); } Commented Oct 8, 2018 at 7:07
  • 1. Hibernate4Module is legacy . 2 SerializationFeature.WRITE_DATES_AS_TIMESTAMPS - not about the question Commented Apr 25, 2020 at 9:27
  • @DmitryKaltovich ad 1) it wasn't legacy at the time of writing; ad 2) ok, removed. Commented Apr 25, 2020 at 9:34
  • Is it possible to update this post for spring boot 3.x ? thanks Commented May 1 at 16:13
-4

Another solution for spring boot: configuration: spring.jpa.open-in-view=true

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.