How do I update an entity using spring-data-jpa?

后端 未结 10 1882
眼角桃花
眼角桃花 2020-11-29 15:12

Well the question pretty much says everything. Using JPARepository how do I update an entity?

JPARepository has only a save method, which does not t

10条回答
  •  情书的邮戳
    2020-11-29 15:53

    Since the answer by @axtavt focuses on JPA not spring-data-jpa

    To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER

    Spring-data-jpa supports update operation.
    You have to define the method in Repository interface.and annotated it with @Query and @Modifying.

    @Modifying
    @Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
    void setUserInfoById(String firstname, String lastname, Integer userId);
    

    @Query is for defining custom query and @Modifying is for telling spring-data-jpa that this query is an update operation and it requires executeUpdate() not executeQuery().

    You can specify other return types:
    int - the number of records being updated.
    boolean - true if there is a record being updated. Otherwise, false.


    Note: Run this code in a Transaction.

提交回复
热议问题