SpringMVC+Hibernate控制器返回json时的坑

坑1:
Spring3.x和Spring4.xSpring5.x使用的不是同样的jar包
正确的如下:

spring-mvc.xml
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean
            class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json; charset=UTF-8</value>
                    <value>application/x-www-form-urlencoded; charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
pom.xml
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>

坑二,如果返回的数据是直接从Hibernate获取到的,那么需要在类上加一个注解:@JsonIgnoreProperties({“hibernateLazyInitializer”, “handler”})
因为Hibernate会自动插入一个属性
坑三:死循环要去掉一个字段,本来以为这样写@JsonIgnoreProperties({“hibernateLazyInitializer”, “handler”,”一个Set属性”})
结果不起作用,查了半天,特么的,这个用法只支持1.x的jackson版本!虽然2.x也有这个类,但是没有了这个功能!
换成1.x版本后,发现jackson的命名有问题,
一个好好的字段,给我反射成这样,依然报错…
这里写图片描述
这里写图片描述

我决定还是放弃1.x版本吧….

解决办法:最好使用VO返回吧,坑太多了,而且,myeclipse逆向工程生成的实体,首字母是T的话,有坑,有的字段不遵循驼峰命名!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

不甘心:终于找到了终极解决:
使用的最新版的jackson
没有用1.x
用的上面的
类上加:@JsonIgnoreProperties(value={“hibernateLazyInitializer”,”handler”})
一对多关系中get方法上加:@JsonIgnore

猜你喜欢

转载自blog.csdn.net/howroad/article/details/80261102