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

相关推荐
spencer_tseng1 分钟前
‘<>‘ operator is not allowed for source level below 1.7
java
人道领域6 分钟前
Day | 07 【苍穹外卖:菜品套餐的缓存】
java·开发语言·redis·缓存击穿·springcache
m0_706653237 分钟前
数据库与缓存操作策略:数据一致性与并发问题
java·数据库·缓存
独断万古他化7 分钟前
【抽奖系统开发实战】Spring Boot 活动模块设计:事务保障、缓存优化与列表展示
java·spring boot·redis·后端·缓存·mvc
BioRunYiXue10 分钟前
甘油不够了,能用植物油保存菌种吗?
java·linux·运维·服务器·网络·人工智能·eclipse
y = xⁿ14 分钟前
【黑马点评二刷日记】分布式锁和Redisson
java·redis·分布式·缓存
空空kkk15 分钟前
JVM面试知识点总结
java·jvm·面试
zdl68621 分钟前
spring Profile
java·数据库·spring
m0_7066532322 分钟前
数据倾斜全面解析与解决方案探析
java
程序员飞哥25 分钟前
有个同事因为恐惧 AI 要离职了
java·后端·程序员