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

47 篇文章 0 订阅

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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=?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个不安分的程序员

祝您财源广进

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值