Spring Data Jpa 如何将Postgres中的bigint值写入StringKotlin字段?

q35jwt9p  于 2024-01-09  发布在  Spring
关注(0)|答案(1)|浏览(298)

我正在使用Kotlin和spring数据。我有一个表,列“phone”在数据库中是BIGINT类型,但在我的@Table类中,这个字段是String类型(val phone: String)。所以当我尝试使用spring数据仓库从DB获取一些记录时,我得到了PostgresqlBadGrammarException: operator does not exist: bigint = character varying。我如何在不改变类型的情况下修复它?我相信一定有一些注解转换器或其他东西。
我尝试在spring数据仓库中创建自定义查询,并将选择结果转换为varchar -“SELECT phone::varchar from table...“,但它不起作用。

UPD我成功配置了自定义转换器:

  1. @Configuration
  2. @EnableR2dbcRepositories
  3. class R2dbcConfiguration {
  4. @Bean
  5. fun r2dbcCustomConversions(
  6. stringToBigIntConverter: StringToBigIntConverter,
  7. bigIntToStringConverter: BigIntToStringConverter
  8. ): R2dbcCustomConversions {
  9. return R2dbcCustomConversions(listOf(stringToBigIntConverter, bigIntToStringConverter))
  10. }
  11. }

字符串
自定义转换器:

  1. @Component
  2. @WritingConverter
  3. class BigIntToStringConverter: Converter<Long, String> {
  4. override fun convert(source: Long): String {
  5. return source.toString()
  6. }
  7. @Component
  8. @WritingConverter
  9. class StringToBigIntConverter: Converter<String, Long> {
  10. override fun convert(source: String): Long {
  11. return source.toLong()
  12. }
  13. }


但是现在它试图将每个字符串字段转换为BIGINT,反之亦然。我如何只对特定实体中的特定字段应用转换器?

bprjcwpo

bprjcwpo1#

要将PostgreSQL BIGINT列Map到Spring Data中的KotlinString字段而不更改类型,您可以使用自定义属性转换器。属性转换器用于将数据库列类型转换为Java/Kotlin类型,反之亦然。
以下是如何为您的案例创建自定义属性转换器:
1.为您的自定义属性转换器创建一个Kotlin类。这个类应该实现javax.persistence.AttributeConverter接口。在您的示例中,您希望在Long(Kotlin中的BIGINT)和String之间进行转换。下面是一个示例:

  1. import javax.persistence.AttributeConverter
  2. import javax.persistence.Converter
  3. @Converter(autoApply = true)
  4. class BigIntToStringConverter : AttributeConverter<Long, String> {
  5. override fun convertToDatabaseColumn(attribute: Long?): String? {
  6. return attribute?.toString()
  7. }
  8. override fun convertToEntityAttribute(dbData: String?): Long? {
  9. return dbData?.toLong()
  10. }
  11. }

字符串
1.用@ConverterautoApply = true注解BigIntToStringConverter类。这告诉JPA自动将此转换器应用于实体中Map到String的所有Long类型的属性。
1.在实体类中,如果字段@Column与属性名称不同,则使用@Column注解phone字段以指定列名。下面是一个示例:

  1. import javax.persistence.Column
  2. import javax.persistence.Entity
  3. import javax.persistence.Id
  4. import javax.persistence.Table
  5. @Entity
  6. @Table(name = "your_table_name")
  7. data class YourEntity(
  8. @Id
  9. val id: Long,
  10. @Column(name = "phone")
  11. val phone: String
  12. )


通过这种设置,Spring Data应该能够在从数据库检索数据时自动处理BIGINT和String之间的转换。
确保将your_table_name替换为表的实际名称,并调整实体类以匹配特定的数据库模式。

展开查看全部

相关问题