You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot + JPA 向Redshift写入数据时自增ID字段无法保存的问题排查求助

Spring Boot + JPA 向Redshift写入数据时自增ID字段无法保存的问题排查求助

大家好,我最近在开发Spring Boot应用时遇到了一个棘手的问题:尝试通过JPA将数据写入Redshift的student_marks表时,因为自增ID字段的原因抛出了异常,折腾了好一阵没找到解决办法,希望有经验的朋友能帮忙看看。

问题场景

我用Spring Data JPA操作Redshift数据库,实体类里的ID字段用了@GeneratedValue(strategy = GenerationType.IDENTITY)来配置自增,但是调用save()方法时直接报错,提示数据库没有返回原生生成的标识值。

相关代码

1. 实体类代码

@Entity
@Data
@Table(name = "student_marks", schema = "staging")
public class StudentMarks{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String subject;
    private Double mark;
    private Instant createdDate;
}

2. Service层保存数据的代码

StudentMarks studentMarks = new StudentMarks();
studentMarks.setName("test");
studentMarks.setSubject("science");
studentMarks.setMark(78.0);
studentMarks.setCreatedDate(Instant.now());
studentMarksRepository.save(studentMarks);

注:这里修正了原代码里的两处笔误:setMarks应为setMark,Instant.now需补充括号为Instant.now()

3. Redshift建表语句

CREATE TABLE IF NOT EXISTS student_marks (
    id BIGINT NOT NULL DEFAULT "identity"(304420, 0, '1,1'::text) ,
    name VARCHAR(200) ,
    subject VARCHAR(20) ,
    mark BIGINT ,
    created_date DATE ,
    PRIMARY KEY (id)
)

抛出的错误日志

Caused by: org.hibernate.HibernateException: The database returned no natively generated identity value
    at org.hibernate.id.IdentifierGeneratorHelper.getGeneratedIdentity(IdentifierGeneratorHelper.java:75)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:62)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3279)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3914)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
    at org.hibernate.engine.spi.ActionQueue.addAction(...)

我的疑问

我查了Redshift的自增字段配置,用的是identity函数来实现自增,但是Hibernate似乎无法识别Redshift返回的自增ID值。是不是Hibernate的方言对Redshift的identity支持有问题?或者我的实体类注解配置不对?有没有办法让JPA正确获取Redshift生成的自增ID?

麻烦大家帮忙分析一下,谢谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 11:13:00