Hibernate在尝试持久化实体时抛出异常

wsewodh2  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(111)

我有一个实体“MyrtyA”,它的id定义如下

@Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
  @SequenceGenerator(name = "sequence", sequenceName = "sequence", allocationSize = 1)
  private Long id;

尝试持久化新条目时,将显示以下日志:

Hibernate: select next value for sequence
Hibernate: insert into dbo.entityA (field1, field2, id) values (?,?,?)
Caused by: java.sql.BatchUpdateException: Cannot insert explicit value for identity column in table 'entityA' when IDENTITY_INSERT is set to OFF.

表定义

IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('dbo.entityA') AND type = 'SO')
BEGIN
CREATE SEQUENCE sequence
    AS BIGINT
    START WITH 1
    INCREMENT BY 1
    MINVALUE 1
    NO MAXVALUE
    CACHE 1000;
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.entityA') AND type in (N'U'))
BEGIN
    CREATE TABLE dbo.entityA(
        id BIGINT NOT NULL CONSTRAINT PK_id PRIMARY KEY DEFAULT (NEXT VALUE FOR sequence),
        field1 varchar(20) not null,
        field2 varchar(20) not null
    );
END

持久化是一个非常基本的创建,

EntityA entityA = new EntityA();
entityA.setField1("test");
entityA.setField2("test);
entityARepository.save(entityA);

我该怎么办?

7tofc5zh

7tofc5zh1#

你基本上复制了id生成。
您的HibernateMap告诉它从一个序列中获取一个新的id,然后在insert语句中使用它。
但是您的表定义试图在插入时创建id本身。
因此,您应该调整您的HibernateMap,不显式生成id,而是依赖数据库来完成此操作。或者,您应该从数据库中的列声明中删除DEFAULT (NEXT VALUE FOR sequence)部分。

相关问题