和Spring MVC打交道的遇错经验

3 篇文章 0 订阅
2 篇文章 0 订阅


  • String类型参数直接用@RequestBody注解会报解析错误
    报错:xxx方法(@RequestBody String id)会报错
    解决:可以用xxx(@RequestBody Map<String, Object> datas),然后从datas中获取参数值datas.get("id"),再转换相应类型。

  • Mybatis关联查询延迟加载报错
    报错:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

原因:使用mybatis的<collection><association>标签时,存在“延迟加载”这个概念。 如果一个实体类的某个属性是其它实体类的类型,且项目中使用了延迟加载(mybatis默认使用了 延迟加载),这就会出现在处理类时,它的属性还没有被序列化,导致如上bug的出现。
解决:
在主动关联的实体类(并非是作为属性的实体类 )的类头(接口头)上加上@JsonIgnoreProperties(value = {"handler"})注解
如在下面例子中的Recommend类上加注解:

    <resultMap type="com.zz.model.Recommend" id="mRecommend">
        <id property="id" column="rec_id"/>
        <result property="title" column="rec_title"/>
        <association property="user" javaType="com.zz.model.Muser" column="rec_userId" select="getMuser">
        </association>
    </resultMap>
//json序列化时忽略bean中的一些属性序列化和反序列化时抛出的异常
@JsonIgnoreProperties(value = {"handler"})
@TableName("recommend")
public class Recommend implements Serializable {

    ……

        /**
     * @备注:推荐人id
     * @字段:user_id BIGINT(19)
     */
    private java.lang.Long userId;
    /**
     * 备注:推荐人(并非数据库中的字段)
     */
    @TableField(exist = false)

    ……
}

其他解法(自定义 com.fasterxml.jackson.databind.ObjectMapper 类):
Spring MVC 解决 Could not write JSON: No serializer found for class java.lang.Object
Spring and jackson, how to disable FAIL_ON_EMPTY_BEANS through @ResponseBody



  • 前台传日期字符串到SpringMVC报400错误
    解决:加入对应格式(如yyyy-MM-dd HH:mm:ss)的时间格式化注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
    /**
     * @备注:开始日期
     * @字段:start_date DATETIME(19)
     */
    @JsonSerialize(using=DateJsonSerializer.class)
    @JsonDeserialize(using=DateJsonDeserializer.class)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
    private java.util.Date startDate;


    /**
     * @备注:结束日期
     * @字段:end_date DATETIME(19)
     */
    @JsonSerialize(using=DateJsonSerializer.class)
    @JsonDeserialize(using=DateJsonDeserializer.class)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
    private java.util.Date endDate;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值