【J2EE】SpringMVC JSON对于外键处理办法

    xiaoxiao2021-03-25  96

    对于web应用程序的异步请求,我们通常使用json数据格式返回,今天在SpringMVC控制器返回Json数据遇到一些问题,在这里做一个总结。

    问题描述:

    大致有有外键关系的实体可能出现循环读取导致栈溢出的问题; 有些字段需要,有些字段用不到,即不需要; 还有就是 LAZY 的属性读不到的问题。

    解决办法:

    首先导致循环读的问题,是由于两个有关系的实体你中有我,我中有你导致的,比如说一个一对多的关系中 一方是持有多方的集合的而多方是持有一方的对象的。 这时我们需要使用到 @JsonIgnore 和 @JsonIgnoreProperties 这两个注解帮助我们解决问题 @JsonIgnoreProperties 此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。 @JsonIgnore 此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。 我们需要做的是在我们的所有的pojo**类上**打上

    @JsonIgnoreProperties(value={“hibernateLazyInitializer”,”handler”,”fieldHandler”})

    然后在所有的Set或List集合的属性或者get方法上面打上@JsonIgnore的注解

    @Entity @Table(name = "computer", catalog = "computer") @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"}) public class Computer implements java.io.Serializable { @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "hardwareId") @JsonIgnore public Set<Hardware> getHardwares() { return this.hardwares; } ... }

    最后就是关于fetch = FetchType.LAZY属性的处理方法,最好是使用openSessionInView,在web.xml中加入过滤器

    <filter> <filter-name>opensessioninview</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>opensessioninview</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

    最后

    应该有不少小伙伴在使用maven构建一个新的项目运行时会出现很多ClassNotFound之类的错误,建议将这个错误后面的类的全名(包括包信息)丢到搜索引擎中看是哪个jar包里的类然后去 仓库网站 上去搜索到引用信息再重新构建。

    转载请注明原文地址: https://ju.6miu.com/read-16722.html

    最新回复(0)