首页 文章

将hibernate对象转换为json时出现stackoverflow错误

提问于
浏览
1

我有一个用户对象具有以下hibernate映射,这是一个多对多的自连接:

<hibernate-mapping>
        <class name="User" table="User">
            <id name="id" type="int">
            <column name="userId" />
                <generator class="native" />
            </id>
            <set name="friends" table="User_Friend" 
                    inverse="false" lazy="true" cascade="all">
                <key column="userId"/>
                <many-to-many column="friendId" class="User" />
            </set>
            <set name="cars" table="Car" inverse="true" fetch="select" lazy="true">
            <key>
                <column name="userId" not-null="true" />
            </key>
            <one-to-many class="Car" />
        </set>
        </class>
    </hibernate-mapping>

汽车映射如下所示:

<hibernate-mapping>
    <class name="Car" table="Car">
        <id name="id" type="int">
            <column name="carId" />
            <generator class="native" />
        </id>
        <set name="carStatuses" table="Car_Status" 
                inverse="true" lazy="true" fetch="select">
            <key>
                <column name="carId" not-null="true" />
            </key>
            <one-to-many class="CarStatus" />
        </set>
        <many-to-one name="user" 
        column="userId"
        not-null="true"/>

    </class>
</hibernate-mapping>

我检索用户对象,然后尝试使用此方法将其作为Restlet JSON表示形式返回:

public Representation getJSONRepresentationFromObject(
            User object) {


        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject(object);

        ja.put(jo);

        JsonRepresentation jr = new JsonRepresentation(ja);
        jr.setCharacterSet(CharacterSet.UTF_8);

        return jr;
    }

问题是我得到一个stackoverlfow错误:

警告:在java.lang.reflect.Method上的sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)的sun.reflect.GeneratedMethodAccessor74.invoke(未知来源)中的资源java.lang.StackOverflowError中捕获到异常或错误 . 在org.json.Jop对象(JSONObject.java:272)的org.json.Jop对象(JSONObject.java:272)org.json.JSONObject.wrap(JSONObject.java)中调用(Method.java:597)org.json.JSONObject.populateMap(JSONObject.java:988) 1587)org.json.JSONArray . (JSONArray.java:158)org.json.JSONObject.wrap(JSONObject.java:1569)atg.json.JSONObject.populateMap(JSONObject.java:990)atg.json位于org.json.JSONArray的org.json.JSONObject.wrap(JSONObject.java:1587)的.JSONObject . (JSONObject.java:272) . (jSONArray.java:158)org.json.JSONObject.wrap(JSONObject . java:1569)org.json.JopObject上的org.json.JSONObject.populateMap(JSONObject.java:990) . (JSONObject.java:272)

如果我删除用户映射中设置的汽车,则错误消失,我可以将用户转换为json . 汽车映射是否存在问题,将其抛入无限循环?

1 回答

  • 0

    问题是Car对象具有对User / Friend对象的后引用 . 我在这里解决了这个问题:

    Hibernate Object not detaching

    Answer :从休眠中拉取对象 . 创建单独的java对象 . 循环遍历对象并使用hibernate对象值填充新创建的对象 .

相关问题