将 UUID 作为 blob 转换为正确的字符串 ID 休眠



我在实体中使用UUID是我的id (@Id(。像这样:

import java.util.UUID;
@Table(name="address_book")
@Entity  
public class AddressBook {  
@Id
private UUID id;
private String name;
.
.
.
}

现在发生的事情是,当我调用addressBookDao.save(addressBook(或每当我将数据保存在数据库中时,它都会被存储为:

id, name, isbn, date, username
{blob}, john, isbn-45888, 15-02-2019, david

因此,在id列中,我将这个blob写入我插入的每一行中。我以为 UUID 会生成一个随机 id,而不是它将 UUID 的整个 json 对象作为 blob 存储在该 id 列中。

我该如何解决这个问题。我希望存在字符串/随机值而不是 blob/对象?

您需要设置正确的休眠生成器,例如

@Id
@GeneratedValue(generator = “UUID”)
@GenericGenerator(
name = “UUID”,
strategy = “org.hibernate.id.UUIDGenerator”,
)
private UUID id;

你真的是指 BLOB 吗?UUID 是 128 位,当然不符合 LOB 列的条件。 例如,您可以在 MySQL 中使用 Binary(16( 列。

现在要回答您的问题,您需要告诉休眠如何生成 ID 值。

@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "hibernate-uuid", strategy = "uuid2")
@Column(name = "id", columnDefinition = "BINARY(16)")
protected UUID id;
import java.util.UUID;
@Table(name="address_book")
@Entity  
public class AddressBook {  
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "name", updatable = false, nullable = false, columnDefinition = "VARCHAR(36)")
@Type(type = "uuid-char")
private String name;
.
.
.
}

这肯定会奏效。它对我有用,请参阅 https://www.codementor.io/@petrepopescu/how-to-use-string-uuid-in-hibernate-with-mysql-1jrhjh6ef5 以获取更多详细信息。

最新更新