我对映射到 HSQLDB 中的表的实体中的 id 字段有以下定义。
...
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ID")
private Integer id;
...
但这似乎并没有生成唯一的 id;而是尝试将 null 插入到导致失败的列中。如果我手动创建一个序列和生成策略来使用该序列,那么数据将按预期持久化。
auto 的生成策略是否意味着提供者(在本例中为 hibernate )将自动选择正确的方法并根据需要完成所有繁重的工作(创建序列、使用 native 方法或适用于该特定平台的任何方法) )?我的理解有误吗?
最佳答案
Doesn't a generation strategy of auto imply that the provider (hibernate in this case) will automatically choose the correct approach and do all the heavy lifting as needed (create sequence, use a native approach or whatever works for that particular platform)? Is my understanding incorrect?
理论上是这样(它默认为 HSQLDB 的 IDENTITY)并且对我有用。这就引出了以下问题:
- 您使用什么方言(以防万一)?
- 您是如何创建表格的?
- 您能否展示 DDL(如果需要,激活
org.hibernate.tool.hbm2ddl
的日志记录)? - 如何插入(通过 Hibernate 的 API,对吧?)?
这是使用 HSQLDB 时实体 Foo
的示例 DDL:
create table Foo (
id bigint generated by default as identity (start with 1),
bar varchar(100),
primary key (id)
)
I created the table using the HSQL DB manager. Just normal create table address... I had not set the id column as identity in my case - just set it as primary key.
然后你就有了答案,使用 IDENTITY
列。
虽然 Hibernate 确实选择了正确的策略并生成了适当的 INSERT
语句(将 null
传递到 id 中,该 id 预计将被保存到 IDENTITY
列),如果您不使用 DDL 生成和导出功能,它不会创建或更改您的物理模型。
关于java - 用于 HSQLDB 的 Hibernate @generatedvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596848/