Spring JPA - 更改已建立的 ID 的数据类型?

问题描述 投票:0回答:1

长话短说,我搞砸了,需要在 Spring 中将 ID 从字符串更改为自动生成的 long,并使用新生成的数字 ID 更新所有子项。我正在尝试使用新的 Flyway 版本来纠正它,但是我必须删除的自动生成的外键名称给我一种感觉,它们在生产中并不相同,并且通常不应该以这种方式进行修改。

进行过渡的适当方式是什么?

编辑:我通过简单地转移到新版本的 id 取得了微小的成功 - 尽管如预期的那样,hibernate 未能为新的 id_v2 父列创建适当的约束(我还在子列中创建了parent_id_v2) .

Error executing DDL "alter table `website$blog` add constraint FK50amru4p1wg4jq0stsw8distc foreign key (website_id_v2) references `website` (id_v2)" via JDBC [Failed to add the foreign key constraint. Missing index for constraint 'FK50amru4p1wg4jq0stsw8distc' in the referenced table 'website'
@Getter @Setter
private String id;
@Getter @Setter @Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id_v2;

再次编辑:以下似乎可以解决该问题,但再次不确定这是否合适

@Table(name="store$website", indexes= @Index(name = "idx_store$website_id_v2", columnList = "id_v2"))
mysql spring spring-boot hibernate spring-data-jpa
1个回答
0
投票

首先在实体中的长 ID 旁边添加一个新列,旁边是现有的字符串 ID。使用 Hibernate 的

@GeneratedValue
自动生成新的 ID。在 Flyway 中创建迁移脚本,通过将现有字符串 ID 转换为长值来填充新列。

在你的实体类中 -

@Entity
@Table(name = "website")
public class Website {
    @Id
    @Column(name = "id")
    private String id;

    @Column(name = "id_v2")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idV2;

    // Optionally add a method to help with conversion if needed
    public Long getConvertedId() {
        return Long.parseLong(id);
    }
}

您的 Flyway 迁移脚本可能如下所示 -

ALTER TABLE website ADD COLUMN id_v2 BIGINT;
UPDATE website SET id_v2 = CAST(id AS BIGINT);
CREATE INDEX idx_website_id_v2 ON website(id_v2);
© www.soinside.com 2019 - 2024. All rights reserved.