Spring-data-jpa saves the entity at the same time

在一次开发中,一个很小的问题,spring-data-jpa在一个事务中同时保存entity对象中出现了,unSupport类型,造成保存不成功,看了几篇blog下,发现大家遇到的问题千奇百怪,没有什么解决方案,看了一下stackoverflow,若有所思,避免以后遇到这些问题省略一下探究,若有喜欢自己解决问题的,可以忽略。


目的:可以同时保存entity
前提:一个事务中根据刚生成的entity对象获取对象的id做一些更新
实现:先保存entity对象,然后拿到对象的id做一些操作,然后在写@Query用原生的方式做操作
@Modifying
@Query(value = "update users set ip_phone = :ipPhone where id = :id", nativeQuery = true)
void updateIpPhoneByUserId(@Param("ipPhone")String ipPhone, @Param("id")Long id);


 



做事情的时候,先考虑一下hibernate的几种状态,临时态,持久态,游离态之间的转换

错误1: 使用jpa自带的SaveAndFlush先保存刷新,这样就可以用其状态保存了,不可行;
错误2: 使用拆分,先保存entity,然后通过另一个方法,findOne查询出来,在做操作,不可行;

 Finally, I used the @Modify @Query method. The sql native method has been updated. There may be other better methods. Record it here. Maybe there is a better way to update in the future.

Guess you like

Origin blog.csdn.net/chajinglong/article/details/86291107