SpringBoot JPA not-null property references a null or transient value 问题解决

. ____ _ __ _ _

/\\ / _' __ _ () __ __ _ \ \ \ \

( ( )\___ | '_ | '| | ' \/ _` | \ \ \ \

\\/ _)| |)| | | | | || (| | ) ) ) )

' || .__|| ||| |\__, | / / / /

=========||==============|/=///_/

:: Spring Boot :: (v2.7.13)

问题描述:

使用JPA编辑实体时报错:

not-null property references a null or transient value : com.psquare.book.entity.system.Role.createAt; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : com.psquare.book.entity.system.Role.createAt

解决方法:

报错的字段恰好时更新时不需要的字段,在字段对应的@Column注解中设置updatable=false解决

复制代码
@Column(nullable = false, updatable = false)
private Date createAt;
@Column(nullable = false, length = 50, updatable = false)
private String createBy;

也可以先使用ID获取当前需要更新的实体,然后修改需要更新的字段后再使用save保存,这样每次更新都是全字段,如果字段比较多对数据库性能会有影响。可以在实体类上使用@DynamicUpdate注解,这样hibernate在生成更新SQL时就只包含值有变更并且不为null的字段。 但这样如果在当前事务中没有获取过当前实体,Hibernate会先查询下数据库,以便获取到实体进行字段对比。

未使用@DynamicUpdate注解生成的更新SQL edit:test_hot3

Hibernate: select role0_.id as id1_1_0_, role0_.create_at as create_a2_1_0_, role0_.create_by as create_b3_1_0_, role0_.update_at as update_a4_1_0_, role0_.update_by as update_b5_1_0_, role0_.description as descript6_1_0_, role0_.name as name7_1_0_ from role role0_ where role0_.id=?

Hibernate: update role set update_at=?, update_by=?, description=?, name=? where id=?

添加@DynamicUpdate

复制代码
@DynamicUpdate
public class Role

使用了@DynamicUpdate注解后生成的更新SQL edit:test_hot4

Hibernate: select role0_.id as id1_1_0_, role0_.create_at as create_a2_1_0_, role0_.create_by as create_b3_1_0_, role0_.update_at as update_a4_1_0_, role0_.update_by as update_b5_1_0_, role0_.description as descript6_1_0_, role0_.name as name7_1_0_ from role role0_ where role0_.id=?

Hibernate: update role set update_at=?, name=? where id=?
使用了@DynamicUpdate注解后,在service中先load再更新 生成的SQL edit:test_hot5

Hibernate: update role set update_at=?, name=? where id=?

相关推荐
wuminyu2 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
txxzjmzlh2 小时前
SpringBoot 配置⽂件
java·spring boot·spring
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3273 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕3 小时前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
三无少女指南4 小时前
从这里开始:Java 后端与 AI 工程的三条阅读路线
java·学习路线·ai工程
香蕉大香蕉(06敬畏市场)5 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
nice_lcj5205 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
骑着蜗牛撵大象3276 小时前
2026 后端 AI 工程化:Spring AI 管调用、MCP 管工具、Agent 内嵌管自治
java·人工智能·后端·spring·ai·可观测性·mcp
tryxr6 小时前
JVM 垃圾回收机制
java·jvm·gc·垃圾回收