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

Spring Data JPA原生查询传Null参数触发ORA-00932类型不一致异常

Spring Data JPA原生查询传入Null参数触发ORA-00932异常

当使用Spring Data JPA执行原生查询时,传入sysId=123可正常执行,但传入sysId为Null时,触发如下异常:

Caused by : java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY

相关代码

ExampleRepository 接口

public interface ExampleRepository extends JpaRepository {

    public static final String FINDSQL = " select a, b, c from exp_attr ea, dep_attr da  where ea.id = da.id AND ea.sysId = :sysId";

    @Query(value = FINDSQL , nativeQuery=true)
    List<ProjectionInterface> getExampleDetails(@Param("sysId") Integer sysId);
}

RestApi 类

public class RestApi {

    @Autowired
    private ExampleRepository exampleRepository;

    public String testJpaRepo(){
        Integer sysId = 123; // 改为Null时触发异常
        exampleRepository.getExampleDetails(sysId);
        return "success";
    }
}

ProjectionInterface 投影接口

public interface ProjectionInterface {
 
 Integer getA();

 String getB();

 String getC();

}

解决方案

问题根源在于Oracle对Null参数的处理逻辑:当sysId为Null时,ea.sysId = :sysId的写法会导致参数类型不匹配,Oracle将Null参数解析为BINARY类型,与数据库中sysId的NUMBER类型冲突。

修改原生SQL语句,添加Null值的判断逻辑即可解决:

public static final String FINDSQL = " select a, b, c from exp_attr ea, dep_attr da  where ea.id = da.id AND (:sysId IS NULL OR ea.sysId = :sysId)";

这个修改的逻辑是:

  • 当sysId为Null时,(:sysId IS NULL)条件成立,此时仅过滤ea.id = da.id的数据
  • 当sysId有值时,ea.sysId = :sysId生效,执行原有的匹配逻辑

这样既兼容了Null参数的场景,又保留了原有非Null参数的查询逻辑,同时避免了类型不匹配的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:55:17