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

q35jwt9p  于 9个月前  发布在  Spring
关注(0)|答案(1)|浏览(156)

我正在使用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我成功配置了自定义转换器:

@Configuration
@EnableR2dbcRepositories
class R2dbcConfiguration {
    @Bean
    fun r2dbcCustomConversions(
        stringToBigIntConverter: StringToBigIntConverter,
        bigIntToStringConverter: BigIntToStringConverter
    ): R2dbcCustomConversions {
        return R2dbcCustomConversions(listOf(stringToBigIntConverter, bigIntToStringConverter))
    }
}

字符串
自定义转换器:

@Component
@WritingConverter
class BigIntToStringConverter: Converter<Long, String> {
    override fun convert(source: Long): String {
        return source.toString()
    }

@Component
@WritingConverter
class StringToBigIntConverter: Converter<String, Long> {
    override fun convert(source: String): Long {
        return source.toLong()
    }
}


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

bprjcwpo

bprjcwpo1#

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

import javax.persistence.AttributeConverter
import javax.persistence.Converter

@Converter(autoApply = true)
class BigIntToStringConverter : AttributeConverter<Long, String> {

    override fun convertToDatabaseColumn(attribute: Long?): String? {
        return attribute?.toString()
    }

    override fun convertToEntityAttribute(dbData: String?): Long? {
        return dbData?.toLong()
    }
}

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

import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table

@Entity
@Table(name = "your_table_name")
data class YourEntity(
    @Id
    val id: Long,

    @Column(name = "phone")
    val phone: String
)


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

相关问题