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

不使用级联类型解决一对一关联中的TransientPropertyValueException问题【已解决】

问题:保存Student时出现关联瞬态实例异常

实体类定义

Student实体

@Entity
@Table(name="student")
public class Student{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
 
  @OneToOne
  @JoinColumn(name="dept_id")
  private Department department;
}

Department实体

@Entity
@Table(name="department")
public class Department{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
 
  @Column(unique=true)
  private String departmentName;
}

问题场景与异常

MySQL数据库中已预先存入若干Department数据,添加学生时从下拉列表选择已存在的Department,但保存Student时抛出如下异常:

object references an unsaved transient instance - save the transient instance before flushing

需求说明

  • 不希望通过添加CascadeType.ALL解决问题,因为保存Student时重复保存已存在的Department会因departmentName字段唯一导致失败
  • 不希望删除Student时关联的Department被删除
  • 仅需查询时返回包含关联Department信息的Student列表

问题解决

问题已解决,原因是传递给Student的Department对象的id为null。

内容的提问来源于stack exchange,提问作者B.Ahmad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:15:51