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

Spring JPA保存单个实体时清空PostgreSQL全表数据问题求助

问题描述

执行JPA保存操作后,PostgreSQL的detail_block表所有现有数据被清空,日志无异常信息,但预期仅新增一条记录。

实现类保存代码

detailBlockEntity.setLastUpdateUserId(ctx.getUserId());
detailBlockEntity.setOriginalUserId(ctx.getUserId());
DetailBlockEntity detailtBlockEntityRsp = detailBlockRepository.save(detailBlockEntity);

实体类代码片段

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

@Entity
@Table(
name = "detail_block",
schema = "pcrowner"
)
@TypeDef(
name = "StringJsonObject",
typeClass = StringJsonUserType.class
)
@NamedQuery(
name = "DetailBlockEntity.findAll",
query = "SELECT dtlBlock FROM DetailBlockEntity dtlBlock"
)
public class DetailBlockEntity extends BaseModelEntity {
private static final long serialVersionUID = -12477273943220535090L;
@Id
@GeneratedValue(
generator = "detail_block_seq",
strategy = GenerationType.SEQUENCE
)
@SequenceGenerator(
name = "detail_block_seq",
sequenceName = "detail_block_seq",
allocationSize = 10,
schema = "pcrowner"
)
@Column(
name = "detail_block_id",
unique = true,
nullable = false,
precision = 38
)
private Long id;
@Column(
name = "category_name"
)
private String ctgName;
// 其余属性与方法省略
排查方向及可能原因
  • 检查父类BaseModelEntity:查看父类是否包含@PrePersist、@PreUpdate等生命周期注解,或是存在误写的删除逻辑,导致插入时触发全表清空操作。
  • Repository自定义逻辑:确认detailBlockRepository是否正确继承JpaRepository/CrudRepository,是否有重写save方法,或是自定义查询中意外包含删除语句。
  • 事务边界问题:检查当前保存操作所在的事务中,是否还有其他执行批量删除、清空表的代码,事务提交时这些操作与保存一起执行。
  • Hibernate DDL配置:核对Spring Boot配置项spring.jpa.hibernate.ddl-auto,若设置为create或create-drop,会在启动或特定时机重建表并清空数据;排查是否有代码动态触发了DDL操作。
  • 数据库触发器:检查PostgreSQL表是否存在异常触发器,可通过以下SQL查询:
    SELECT * FROM pg_trigger WHERE tgrelid = 'pcrowner.detail_block'::regclass;
    
    确认是否有插入新记录时触发清空表的触发器逻辑。
  • 序列与主键冲突:检查序列detail_block_seq的当前值是否与表中现有主键最大值冲突,极端情况下可能导致Hibernate执行异常操作(通常会抛出异常,但需排查)。

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:25:17