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=?

相关推荐
微三云、小叶7 分钟前
排队免单系统底层设计:四种分配算法拆解,无预支资金的合规营销架构方案
java·前端·软件开发·商业模式·本地生活·商业思维
就叫_这个吧10 分钟前
Java+MySQL+Mybatis+Junit4实现学生信息管理系统
java·mysql·mybatis
乐之者v10 分钟前
xxl-job添加执行器
java
可乐ea35 分钟前
【知识获取与分享社区项目 | 项目日记第 19 天】基于 Elasticsearch 实现关键词检索与业务权重排序
java·大数据·spring boot·mysql·elasticsearch·搜索引擎·全文检索
zzz_23681 小时前
【Spring】面试突击系列(一):IoC 与 DI 深度解析
java·spring·面试
于先生吖1 小时前
前后端分离体育服务项目,场馆计费+线下赛事排行小程序部署开发教程
java·小程序·uni-app
RemainderTime1 小时前
Spring Boot脚手架集成 Spring Security实现生产级RBAC鉴权
spring boot·后端·spring
闪电悠米2 小时前
黑马点评-秒杀优化-01_async_seckill_idea
java·数据库·ide·redis·分布式·缓存·intellij-idea
摇滚侠2 小时前
IDEA 创建 Java 项目 lib 和 resources
java·ide·intellij-idea
宸津-代码粉碎机2 小时前
Spring AI企业级Agent实战|多工具自动规划+并行调度落地,彻底解决复杂业务AI任务编排问题
java·大数据·人工智能·spring boot·python·spring