Spring Jpa这项技术在Spring 开发中常常用到。spring
今天在作项目用到了Entity的关联懒加载,可是在返回Json的时候,无论关联数据有没有被加载,都会触发数据序列化,而若是关联关系没有被加载,此时是一个
HibernateProxy
,并非真实的数据,而致使了报错。
例如这个Topic Entity:app
@Entity @Table(name = "yms_topics") @Getter @Setter @NoArgsConstructor @EntityListeners(AuditingEntityListener.class) @JsonInclude(JsonInclude.Include.NON_EMPTY) @NamedEntityGraphs({ @NamedEntityGraph(name = "topic.all", attributeNodes = { @NamedAttributeNode(value = "author"), @NamedAttributeNode(value = "category") }) }) public class Topic implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(targetEntity = User.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User author; @ManyToOne(targetEntity = TopicCategory.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "category_id") private TopicCategory category; @Column(nullable = false, length = 200) private String title; @Lob @Column(nullable = false, length = 50000) private String content; @CreatedDate private Date createdAt; @LastModifiedDate private Date updatedAt; }
author 和 category 都是多对一的关联,也就是做者和分类,定义的是懒加载LAZY
,如今须要分页取出记录,Repository 以下:fetch
@EntityGraph(value = "topic.all") Page<Topic> findAll(Pageable pageable);
这是关联读取author和category数据,没有任何问题。可是若是有的关联不须要加载,将EntityGraph去掉,就会报错。gradle
Page<Topic> findAll(Pageable pageable);
究其缘由就是HibernateProxy 没有办法被序列化,网上有不少的方法,例如JsonIgnoreProperties
,这是治标不治本的方法hibernate
如今要达到的目标是当有关联数据的时候序列化,不存在的时候不返回,或者直接返回Null。code
其实要解决这个问题很简单,那就是使用 Jackson 的一个包 jackson-datatype-hibernate5
。
首先gradle添加依赖:orm
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5', version: '2.9.8'
xml
这个版本要注意jackson-datatype-hibernateX
,根据Hibernate的版原本定开发
而后咱们要重写 SpringMvc的 MappingJackson2HttpMessageConverter
,将Hibernate5Module
这个Module 注册到ObjectMapper
。get
咱们新建一个WebMvcConfig类,以下:
@Configuration public class WebMvcConfig { @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = converter.getObjectMapper(); Hibernate5Module hibernate5Module = new Hibernate5Module(); mapper.registerModule(hibernate5Module); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return converter; } }
这是一个Config类,很简单
MappingJackson2HttpMessageConverter
,获取到ObjectMappermapper.registerModule(hibernate5Module);
注册Module@JsonInclude(JsonInclude.Include.NON_EMPTY)
,否则当数据为null的时候会输出null。到这里咱们就能够达到预期的目的了。
这里可能会致使spring.jackson的配置失效,之后再行研究。