You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ModelMapper映射后获取RequestParam遇空指针异常求助

ModelMapper映射时出现source cannot be null异常的问题排查

我用ModelMapper实现了模型对象与实体对象的双向映射,目前在处理GET请求的RequestParam参数时遇到异常,请求帮忙解决。

报错信息

Hibernate: select c1_0.id, c1_0.email, c1_0.first_name, c1_0.idp_customer_id,
c1_0.last_name, c1_0.phone from customer_entity as c1_0 where c1_0.idp_customer_id = ?
2022-08-04 22:41:10 [http-nio-8040-exec-4] ERROR - [dispatcherServlet]:175: Servlet.service() for servlet [dispatcherServlet] in context with path [/ca] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: source cannot be null] with root cause
java.lang.IllegalArgumentException: source cannot be null

控制器代码

/** GET request to return customer Id_id **/
@RequestMapping( method = RequestMethod.GET)
@ResponseBody
public Customer getCustomerIdpId(@RequestParam(name = "idp_customer_id") String idpCustomerId) {
        return customerMapper.convertToCustomer(customerAccountService.getCustomerIdp(idpCustomerId));
}

CustomerMapper代码

public Customer convertToCustomer(CustomerEntity customerEntity) {
    return modelMapper.map(customerEntity, Customer.class);
}

错误的请求方式(GET请求不应携带请求体)

{
"idpCustomerId": "3940f85e-4601-4870-b30f-c6624e7d4678"
}

问题分析

  1. 异常核心是source cannot be null,说明调用modelMapper.map时传入的customerEntity为null,也就是customerAccountService.getCustomerIdp(idpCustomerId)没有查询到对应数据,返回了null。
  2. 关键问题:你用GET请求携带请求体传递参数,这不符合HTTP规范,后端@RequestParam无法从请求体中获取到idp_customer_id的值,导致查询条件无效,最终返回null。

解决方法

  1. 修正请求方式:GET请求通过URL参数传递值,比如请求地址改为:
    /ca?idp_customer_id=3940f85e-4601-4870-b30f-c6624e7d4678
    
  2. 添加空值校验:在Mapper层增加空判断,避免传入null触发ModelMapper异常:
    public Customer convertToCustomer(CustomerEntity customerEntity) {
        if (customerEntity == null) {
            return null; // 也可根据业务需求返回空的Customer对象
        }
        return modelMapper.map(customerEntity, Customer.class);
    }
    
  3. 检查服务层逻辑:确认customerAccountService.getCustomerIdp方法在参数无效或无匹配记录时的处理逻辑,必要时在控制器层先校验参数是否为空,再调用服务查询。

内容的提问来源于stack exchange,提问作者autoboss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:01:09