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

使用Spring Data JPA的ExampleMatcher.withIgnoreCase()遇无法解决的类型转换错误

Spring Data JPA ExampleMatcher.withIgnoreCase()触发ClassCastException的解决方案

问题概述

使用Spring Data JPA 2.6.7,调用ExampleMatcher.matching().withIgnoreCase("custName")时触发ClassCastException,错误提示为org.hibernate.metamodel.model.domain.internal.SingularAttributeImpl cannot be cast to org.hibernate.metamodel.model.domain.AllowableFunctionReturnType。

原因分析

该错误源于Spring Data JPA 2.6.x版本与Hibernate的API兼容性问题:Spring Data JPA在构建忽略大小写查询时,调用Hibernate的lower()方法时出现类型转换错误,此问题在Spring Data JPA 2.7.x版本中已被修复。

解决方案

方案1:升级Spring Data JPA版本

将Spring Data JPA升级至2.7.x及以上版本(例如2.7.10),该版本修复了与Hibernate的API适配问题。如果使用Spring Boot,对应升级至Spring Boot 2.7.x版本即可自动同步Spring Data JPA版本。

方案2:适配Hibernate版本

若无法升级Spring Data JPA,需确保Hibernate版本与Spring Data JPA 2.6.7兼容。Spring Data JPA 2.6.7对应的兼容Hibernate版本为5.6.x,检查项目依赖,排除冲突的Hibernate版本,引入正确的5.6.x版本。

验证代码(代码本身无问题,版本修复后即可正常运行)

实体类代码:

@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "jpa_customer")
@Getter
@Setter
@ToString
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "customer_id")
    private Long customerId;
    
    @Column(name = "customer_name")
    private String custName;
    
    @Column(name = "customer_address")
    private String custAddress;
}

测试类代码:

@ContextConfiguration(classes = ApplicationConfig.class)
@ExtendWith(SpringExtension.class)
public class QEBTest {
    
    @Autowired
    QBERepositories qbeRepositories;
    
    @Test
    void test() {
        Customer customer = new Customer();
        customer.setCustName("SAN");
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnoreCase("custName");
        Example<Customer> example = Example.of(customer, exampleMatcher);
        System.out.println(qbeRepositories.findAll(example));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:45:44