mysql - 如何在映射到 mysql 中的 varbinary 值的 byte[] hibernate 实体上创建 Id

标签 mysql hibernate orm jpa primary-key

我正在尝试创建一个在 hibernate 状态下具有 byte[12] id 的实体。它似乎不喜欢将 byte[] 作为主键,而作为另一列,它在支持 mysql 数据库中将其设置为一个 tinyblob。我试图创建一个字符串,但问题是 java 中的字符串是每个字符 2 个字节,而在 mysql 中它是每个字符一个字节。我正在寻找这样的东西

@Entity
public class TestClass {
    @Id
    @Column(length=12)
    private byte[] id;
...

像这样映射到一个mysql表

Table 'testclass'
   Column id - varbinary     length 12     primary key
    ...

我已经尝试了多种不同的方法(主要是尝试摆弄字符串)来做到这一点,但它似乎无法正常工作。有没有人能够做到这一点?谢谢。

最佳答案

如您所见,标准 JPA 不支持此功能。来自规范:

2.1.4 Primary Keys and Entity Identity

...

The primary key (or field or property of a composite primary key) should be one of the following types: any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date; java.sql.Date. In general, however, approximate numeric types (e.g., floating point types) should never be used in primary keys. Entities whose primary keys use types other than these will not be portable. If generated primary keys are used, only integral types will be portable. If java.util.Date is used as a primary key field or property, the temporal type should be specified as DATE.

话虽如此,您似乎可以在 byte[] 周围使用包装器类型并实现自定义用户类型。 UserType for a byte[] identifier property wiki 页面提供了一个实现。

引用章节2.4.3.2. Type的 Hibernate 注释文档来声明和使用带有注释的自定义类型。

引用资料

  • JPA 1.0 规范
  • 第 2.1.4 节“主键和实体标识”
  • Hibernate 注释引用指南
  • 2.4.3.2. Type

资源

关于mysql - 如何在映射到 mysql 中的 varbinary 值的 byte[] hibernate 实体上创建 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3686008/

相关文章:

java - Hibernate native 查询可选参数抛出 'operator does not exist: bigint = bytea'

java.lang.ClassCastException : java. lang.Long 无法在 java 1.6 中转换为 java.lang.Integer

php - POST 问题

php - mysql_fetch_assoc() : supplied argument is not a valid MySQL result resource

php - 有 ORM 框架支持跨数据库/跨服务器连接吗?

mysql - 你能在 mysql 中存储 facebook 点赞吗?

hibernate - 未配置 CurrentSessionContext! : ThreadLocalSessionContext. 绑定(bind)( session );没有正确绑定(bind)我的 session

java - JPA:如何覆盖@Embedded属性的列名

python - 如何使用SQLAlchemy设置和获取关系记录?

rest - 虚拟字段未出现在 REST JSON 结果中