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

标签 spring hibernate jackson mapping lazy-evaluation

在我使用 Hibernate 5 和基于 Java 的配置的 Spring 4 项目中,每次 Jackson 尝试使用惰性集合序列化我的实体时,我都会遇到异常“无法初始化代理 - 无 session ”。 jackson 似乎无法检查集合是否懒惰并触发加载从而生成异常。 我如何让 Jackson 避免对每个 @Entity 类上的每个延迟加载集合进行序列化,从而避免不断出现异常并因“无 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<>();
}

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

此处出现异常(在 Controller 中):

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

最佳答案

jackson-datatype-hibernate插件确实解决了问题。 我只是将 HibernateAwareObjectMapper 添加为一个单独的类:

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 方法:

@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 
}

关于spring - Jackson:从序列化中排除@Entity 类上的每个惰性集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232264/

相关文章:

java - Jersey 未调用 JsonParseExceptionMapper

java - SpringMVC + Hibernate Tomcat 500,json 无堆栈跟踪

java - spring mvc 与 jpa 中的 Multi-Tenancy 架构

spring - 是否可以使用 Spring 的缓存抽象和 redis 创建多个缓存存储?

java - Hibernate @OneToMany 映射给出异常,

java - Hibernate:更新 OneToMany 关系

spring - EL 自动完成/代码协助 Eclipse 和 Spring Beans

hibernate - 在grails的单个应用程序中连接不同的数据库(动态)

java - 将对象添加到 json 文件中对象的 JsonArray

java - 使用 Jackson 是否可以忽略所有循环关系而无需添加注释?