【问题标题】:Liquibase generates bigint IDs instead of varcharLiquibase 生成 bigint ID 而不是 varchar
【发布时间】:2013-06-12 16:35:06
【问题描述】:

我只是在 PostgreSQL 上尝试使用 Dropwizard 和 Hibernate 的 Liquibase,所有最新版本,但我遇到了障碍。我打算为我的类 ID 使用 Hibernate 的 UUID 生成器,它会生成一个字符串 PK。我指定我想要一个名为idvarchar(32) 字段在我的表中,但Liquidbase 生成了bigint 字段。然而有趣的是,这两个表有不同的列:portfolio.id 有序列portfolio_id_seq,而 Stock 没有序列。

我是不是做错了什么,或者这只是 Liquibase 的 ID 列的一些奇怪属性?我应该使用bigints 吗?代码如下:

migrations.xml:

<changeSet id="1" author="orlade">
    <createTable tableName="stock">
        <column name="id" type="varchar(255)">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="name" type="varchar(255)">
            <constraints nullable="false" />
        </column>
        <column name="symbol" type="varchar(255)">
            <constraints nullable="false" />
        </column>
        <column name="description" type="varchar(255)" />
    </createTable>

    <createTable tableName="portfolio">
        <column name="id" type="varchar(255)">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="name" type="varchar(255)">
            <constraints nullable="false" />
        </column>
        <column name="description" type="varchar(255)" />
    </createTable>
</changeSet>

Portfolio.java:

@Entity
@Table(name = "portfolio")
public class Portfolio {
  @Id
  @GeneratedValue(generator = "system-uuid")
  @GenericGenerator(name = "system-uuid", strategy = "uuid")
  private String id;
}

Stock.java:

@Entity
@Table(name = "stock")
public class Stock {
  @Id
  @GeneratedValue(generator = "system-uuid")
  @GenericGenerator(name = "system-uuid", strategy = "uuid")
  private String id;
}

【问题讨论】:

  • 可能没有帮助,但 UUID 不应该是正确使用的类型吗?
  • 好吧,如果你存储 uuid,你不使用序列生成器,你可以在添加 ossp-uuid contrib 模块后设置DEFAULT uuid_generate_v4(),或者让你的应用程序生成它们。听起来您的 ORM 没有收到您想要 UUID 的消息。
  • 确实,如果我使用 UUID,我想我也应该让 Hibernate 知道。这样做之后,它仍然创建了 bigint 列。

标签: database postgresql database-schema liquibase dropwizard


【解决方案1】:

所以虽然我找不到有效 Liquidbase 类型的列表,但事实证明 UUID 是其中之一,所以我使用了它,并将 Java 类型也更改为 java.util.UUID。这似乎足以让 Liquidbase 创建 uuid 类型的列,但后来我开始在 Java 中收到关于无法将字符串写入 UUID 或其他内容的错误。

(或至少一个)解决方案是使用@Type 注释来指定您希望 Hibernate 在写入数据库之前将值转换为的类型。仅仅说它是java.util.UUID 似乎还不够。以下设置有效:

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Type(type = "pg-uuid")
private UUID id;

uuid2 策略可以generate UUID, String or byte[16] values,默认情况下它似乎尝试使用bytea 类型写入 Postgres。指定类型修复了这个问题(根据Postgresql UUID supported by Hibernate?),我也不知道为什么它不是默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2020-08-26
    • 2017-06-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    相关资源
    最近更新 更多