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

Spring Data Kotlin项目H2测试原生查询UUID投影异常

问题:H2数据库下原生查询投影UUID时抛出类型转换异常

Cannot project byte[] to java.util.UUID; Target type is not an interface and no matching Converter found

场景说明

  • 仅在使用H2嵌入式内存数据库的测试或应用运行场景中触发该异常,访问投影的id属性时抛出
  • 生产环境使用PostgreSQL时运行完全正常

推测原因

  • 可能与H2存储UUID的方式、驱动返回数据的格式有关
  • 也可能是Spring的ConversionService中缺少byte[]转UUID的转换器

相关代码

仓库接口

@Repository
interface CustomRepository : JpaRepository<CustomEntity, UUID> {

    @Query("select id from CUSTOM_ENTITY_TABLE", nativeQuery = true)
    fun nativeProjectingQuery() : List<CustomProjection>
}

实体类

@Table(name = "CUSTOM_ENTITY_TABLE")
@Entity
data class CustomEntity (
    @Id
    val id: UUID,
    val someData : String
){}

投影接口

interface CustomProjection {
    var id : UUID
}

测试类

@DataJpaTest
class CustomRepositoryTest {

    @Autowired private lateinit var customRepository: CustomRepository

    @Test
    fun test() {
        val result = customRepository.nativeProjectingQuery()
        assertThat(result[0].id).isNotNull()
    }
}

补充说明

编辑补充:在Spring应用主方法中调用投影并打印id时,同样会出现该异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:55:00