天天看點

@ResponseBody 與Hibernate懶加載LAZY失效的問題

@ResponseBody将Object轉為JSON 如果Object的關聯屬性用了LAZY加載; LAZY将會失效,将關聯資料也查出。這個時候需要給轉換MappingJackson2HttpMessageConverter  的 ObjectMapper注冊Hibernate4Module。

第一步:  需要下載下傳 jackson-datatype-hibernate4-2.23.jar 這個包(注意版本對應)

第二步:建立一個類繼承ObjectMapper(com.fasterxml.jackson.databind包下的);

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;

public class HibernateAwareObjectMapper extends ObjectMapper {
    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }
}
           

第三步: 修改在springmvc的配置檔案applicationContext.xml中節點。

<mvc:annotation-driven>
    <mvc:message-converters>
    <!-- Use the HibernateAware mapper instead of the default -->
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.boleprint.util.HibernateAwareObjectMapper" />
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
           

參考網頁:

http://blog.csdn.net/derek_yule/article/details/53114530

http://blog.csdn.net/liming8291/article/details/42554179

http://blog.csdn.net/sqh201030412/article/details/55511636

http://blog.csdn.net/alan_liuyue/article/details/53433325

http://blog.csdn.net/ms143014/article/details/51436939