【问题标题】:Spring JPA Projection not working with UUID types?Spring JPA Projection 不适用于 UUID 类型?
【发布时间】:2020-05-26 13:50:27
【问题描述】:

我有一个使用 Kotlin 和 Springboot 的项目。 在此项目中,实体具有以下字段:idnameparent。 我想要的是只得到idname。所以我为那个实体做了一个投影界面视图。

这是我的实体:

@Entity
data class Keyword(

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    var id: UUID? = null,

    @Column(columnDefinition = "BINARY(16)")
    var parent: UUID? = null,

    @NotBlank
    var name: String? = null

)

存储库:

@Repository
interface KeywordRepository: JpaRepository<Keyword, UUID> {

    @Query(value = "SELECT keyword.id, keyword.parent, keyword.name FROM keyword LEFT JOIN project_keyword ON project_keyword.keyword_id = keyword.id WHERE project_keyword.project_id LIKE :id", nativeQuery = true)
    fun findAllKeywordsByProjectId(id: UUID): MutableList<KeyWordView>
}

服务:

@Service
class KeywordService (
  private val projectService: ProjectService,
  private val keywordRepository: KeywordRepository
) {

    fun getKeywordsByProjectId(id: UUID): MutableList<KeyWordView> {

        projectService.checkIfProjectExistsById(id)

        return keywordRepository.findAllKeywordsByProjectId(id).toMutableList()
    }
}

我的投影接口类:

interface KeyWordView {

    val id: UUID

    val name: String?
}

当我通过控制器类调用此端点时。我得到这个输出:

 "list": [
      {
        "name": "MARINE MICROBIOTA",
        "id": "0,31,-36,77,29,123,66,-25,-127,-43,-31,83,104,-90,47,10"
      }
    ]

但如果我在KeywordView 界面中将val id: String 更改为val id: UUID,我会收到以下错误:

{
  "code": 500,
  "data": null,
  "message": "Could not write JSON: Projection type must be an interface!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Projection type must be an interface! (through reference chain: no.inmeta.ris.util.response.ResponseDto[\"data\"]->no.inmeta.ris.util.pagination.PageDto[\"list\"]->java.util.ArrayList[0]->com.sun.proxy.$Proxy199[\"id\"])",
  "status": "FAIL"
}

有人知道如何解决这个问题吗?我想接收 UUID 作为 UUID 而不是奇怪的格式。

谢谢!

【问题讨论】:

    标签: sql spring-boot jpa kotlin


    【解决方案1】:

    我猜问题是 UUID 类。正如您的实体所述,您定义了 dir hibernate,即 db 中的列是二进制 (16)。而且我想在接口投影中使用此 UUID 类型不起作用,因为没有有效的映射信息(如何将长度为 16 字节的二进制数据转换为 UUID 类)。所以我假设您必须更改列的类型,或者您必须使用字符串并编写一个函数来转换该字符串。

    另一种可能性是使用您想要的两个列为该表创建第二个实体。并且只需使用第二道,因为您正在使用 yiur 投影。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-21
      • 2023-03-06
      • 2020-06-28
      • 2021-08-28
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多