No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

异常

话不多说,先看异常:

1
1 HTTP Status 500 - Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.agen.entity.User["positionchanges"]->org.hibernate.collection.internal.PersistentSet[0]->com.agen.entity.Positionchange["position"]->com.agen.entity.Position_$$_jvst714_7["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.agen.entity.User["positionchanges"]->org.hibernate.collection.internal.PersistentSet[0]->com.agen.entity.Positionchange["position"]->com.agen.entity.Position_$$_jvst714_7["handler"])

网上找到的解决办法说是因为,hibernate会给每一个被管理的对象加上hibernateLayInitializer属性,同时structs-jsonplugin或者其他的jsonplugin都是。
因为jsonplugin用的是java的”内审机制”,hibernate会给被管理的pojo加入一个hibernateLayInitializer属性,jsonplugin通过java的反射机制将pojo解析为json时,
同时hibernateLazyInitializer属性也进行反射操作,但是hibernateLazyIniyializer无法由反射得到,所以就抛出了异常。

解决方法

  1. 解决方法1
    在pojo类上加入

    1
    @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"}) 

    这行代码的意思就是在转化为json时,忽略value数组中的hibernateLazyInitializer、handler、fieldHandler属性。
    另外你还有其他想要忽略的属性也可以在后便加入。

  2. 解决方法2
    //旧代码

    1
    2
    3
    4
    5
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "roleId", nullable = false)
    public Role getRole() {
    return this.role;
    }

    //新代码

    1
    2
    3
    4
    5
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "roleId", nullable = false)
    public Role getRole() {
    return this.role;
    }