我有一个实体“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);
我该怎么办?
1条答案
按热度按时间7tofc5zh1#
你基本上复制了id生成。
您的HibernateMap告诉它从一个序列中获取一个新的id,然后在insert语句中使用它。
但是您的表定义试图在插入时创建id本身。
因此,您应该调整您的HibernateMap,不显式生成id,而是依赖数据库来完成此操作。或者,您应该从数据库中的列声明中删除
DEFAULT (NEXT VALUE FOR sequence)
部分。