我只是在 PostgreSQL 上使用 Dropwizard 和 Hibernate 尝试 Liquibase,所有最新版本,但我遇到了障碍。我打算为我的类 ID 使用 Hibernate 的 UUID 生成器,它会生成一个字符串 PK。我指定我想要一个名为 id
的 varchar(32)
字段在我的表中,但 Liquidbase 生成了 bigint
字段。然而有趣的是,这两个表有不同的列:portfolio.id
有序列 portfolio_id_seq
,而 Stock 没有序列。
我是不是做错了什么,或者这只是 Liquibase 的 ID 列的一些奇怪属性?我应该使用 bigint
吗?代码如下:
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>
投资组合.java:
@Entity
@Table(name = "portfolio")
public class Portfolio {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
}
股票.java:
@Entity
@Table(name = "stock")
public class Stock {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
}
最佳答案
所以虽然我找不到有效的 Liquidbase 类型列表,但事实证明 UUID
是一个,所以我使用了它,并将 Java 类型更改为 java.util。 UUID
也是。这似乎足以让 Liquidbase 创建类型为 uuid
的列,但随后我开始在 Java 中遇到无法将 String 写入 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? ),我也不知道为什么它不是默认值。
关于database - Liquibase 生成 bigint ID 而不是 varchar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17070767/