Jackson:从序列化中排除@Entity 类 上的每个惰性集合

Jackson: exclude every lazy collection on @Entity classes from serialization

在我使用 Hibernate 5 和基于 Java 的配置的 Spring 4 项目中,每次 Jackson 尝试使用惰性集合序列化我的实体时,我都会遇到异常 "could not initialize proxy - no Session "。杰克逊似乎无法检查集合是否懒惰并触发加载从而生成异常。 我如何让 Jackson 避免在每个 @Entity-class 上对每个延迟加载的集合进行序列化,从而避免不断出现异常并因 "no Session" 而失败?最简单的工作解决方案。 我读过很多方法,其中一些确实为我解决了这个问题。 任何帮助将不胜感激(不适用于 Spring Boot!)。 一些代码片段:

@Data
@Entity
@ToString(exclude="questions")
@Table(name = "theme")
public class Theme {

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id")
    private Long id;

    @Column(name = "title")
    private String title;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @OneToMany // LAZY by default
    @JoinColumn(name = "theme")
    private List<Question> questions;// = new ArrayList<>();
}

DAO

public interface ThemeDAO extends CrudRepository<Theme, Long> {
    List<Theme> findAll();
}

此处出现异常(在控制器中):

 ObjectMapper objectMapper = new ObjectMapper();
 result = objectMapper.writeValueAsString(theme);

jackson-datatype-hibernate 插件确实解决了问题。 我刚刚将 HibernateAwareObjectMapper 添加为单独的 class:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {
            registerModule(new Hibernate5Module());
    }

}

然后覆盖 MVC 配置器中的方法 configureMessageConverters class:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "learning_session.controller" })
public class WebContext extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
            this.applicationContext = applicationContext;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(new MappingJackson2HttpMessageConverter(new HibernateAwareObjectMapper()));
            super.configureMessageConverters(converters);
    }
// more beans 
}