在Spring Data JPA 中使用Update Query更新实体类@DynamicUpdate,@DynamicInsert

对于 Spring Data JPA 进行指定字段进行更新时,可以使用下列代码

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2") 
int setFixedFirstnameFor(String firstname, String lastname);

首先让人奇怪的是,repository method只能返回int或者转为void,因为这个操作只会把数据写入到数据库,但是不会select。
执行完modifying query, EntityManager可能会包含过时的数据,因为EntityManager不会自动清除实体。
只有添加clearAutomatically属性,EntityManager才会自动清除实体对象。

@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId") 
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);

这样是一个解决方案,当然也可以使用动态更新。在实体类上加上注解@DynamicUpdate, @DynamicInsert,这两个注解是jpa的实现hibernate才有的,当jpa的实现为hibernate时,才会生效,当有以上注解时,标记实体sql动态生成,当insert的时候,如果字段为NULL,则生成的sql语句不插入该字段,当update时,如果字段为NULL,则不生成update该字段,前提条件的是,当DynamicUpdate时,需要先执行select然后在update。

但是需要注意的是,当你select后,显示的把某些字段set为NULL,jpa为认为你修改了该字段,同样会生成到update语句中,所以动态的update只是为让update的sql语句减少不必要的null设置,并不能达到自己想要自定义的update。

你可能感兴趣的:(在Spring Data JPA 中使用Update Query更新实体类@DynamicUpdate,@DynamicInsert)