【问题标题】:Hibernate Junit hsqldb - (strategy = GenerationType.AUTO) not workingHibernate Junit hsqldb - (strategy = GenerationType.AUTO) 不工作
【发布时间】:2026-01-15 17:20:08
【问题描述】:

My Dao 层与 MySql 配合得很好。当我尝试对内存数据库(HSQLDB)进行单元测试时,我无法持久化数据。我的实体定义如下

public class Api {
    @Id
    @Column(name = "api_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int apiId;

在尝试持久化时,不会自动生成 id。它作为 null 传递。

18:05:52.071 [main] DEBUG org.hibernate.SQL - insert into api (api_id, description, version) values (null, ?, ?)
18:05:52.076 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not prepare statement [insert into api (api_id, description, name) values (null, ?, ?)]

我的休眠属性是

    Properties properties = new Properties();
    properties.setProperty(ApiConstants.HIBERNATE_DIALECT, "org.hibernate.dialect.HSQLDialect");
    properties.setProperty(ApiConstants.HIBERNATE_DRIVER_CLASS, "org.hsqldb.jdbcDriver");
    properties.setProperty(ApiConstants.HIBERNATE_CONN_URL, "jdbc:hsqldb:mem:apicloud");
    properties.setProperty(ApiConstants.HIBERNATE_CONN_USER, "sa");
    properties.setProperty(ApiConstants.HIBERNATE_CONN_PWD, "");
    properties.setProperty("hibernate.archive.autodetection", "class,hbm");
    properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    properties.setProperty("hibernate.show_sql", "true");

每次触发单元测试时都会创建架构。创建语句如下发出。

18:05:51.995 [main] DEBUG org.hibernate.SQL - create table api 
(api_id integer generated by default as identity (start with 1),
description varchar(255), version varchar(255), primary key (api_id))

如果我遗漏了什么,请告诉我。

【问题讨论】:

  • 您的代码应该可以正常工作。您使用的是哪个版本的 HSQLDB 和 Hibernate?另外,您可以为 org.hibernate 启用调试日志记录并为 Api 模型查找“CREATE TABLE”语句吗?您应该看到该列是使用“身份”创建的 - 如果不是,那是您的问题。
  • 嗨.. 感谢您的回复.. 我的休眠版本是 4.3.6.Final 和 HSQLDB 版本是 2.2.8。我在上面的问题中也添加了 create table 语句,我可以看到该表是使用标识生成的。问题仍然存在。

标签: java mysql hibernate junit hsqldb


【解决方案1】:

当我将 HSQLDB 版本更新到 2.2.9 后问题得到解决。

https://forum.hibernate.org/viewtopic.php?f=1&t=1043498&p=2490106#p2490106

Pradeep。

【讨论】: