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

Data JPA通过示例查询:无法使用Long类型值执行搜索

解决Spring Data JPA Example查询Long类型id无效的问题

这个问题我之前也踩过坑,核心原因是Example查询的默认匹配规则会把未设置值的null属性也纳入查询条件,而你只想要根据id精确匹配,所以才会查不到结果。下面给你几个实用的解决方案:

方案一:配置ExampleMatcher忽略空属性

通过自定义ExampleMatcher,明确告诉JPA只匹配你设置了值的属性,同时指定id的精确匹配规则:

ProductEntity product = new ProductEntity();
product.setId(productId);

// 创建匹配器:忽略所有null属性,只查询有值的字段
ExampleMatcher matcher = ExampleMatcher.matching()
    .withIgnoreNullValues()
    .withMatcher("id", ExampleMatcher.GenericPropertyMatcher::exact); // id精确匹配

Example<ProductEntity> ex = Example.of(product, matcher);
// 后续调用repository的查询方法,比如findOne(ex)

这样生成的SQL只会包含id = ?的条件,不会带上其他null属性的is null判断,就能正确查到目标数据了。

方案二:直接使用主键查询方法(更推荐)

如果你的需求只是根据主键id查询,完全没必要用Example,Spring Data JPA已经提供了更高效的原生方法:

Optional<ProductEntity> productOpt = productRepository.findById(productId);
if (productOpt.isPresent()) {
    ProductEntity targetProduct = productOpt.get();
    // 你的业务逻辑
}

这种方式不仅代码更简洁,还能利用JPA对主键查询的优化,性能比Example更好。

方案三:显式忽略不需要匹配的字段

如果因为业务场景必须用Example,也可以直接指定忽略其他不需要匹配的字段:

ExampleMatcher matcher = ExampleMatcher.matching()
    .withIgnorePaths("model") // 忽略model字段,只匹配id
    .withMatcher("id", match -> match.exact());

Example<ProductEntity> ex = Example.of(product, matcher);

这种方式适合当你有多个属性,但只想匹配其中特定字段的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:43:40