hibernatejpajpql

Get the number of records updated after executing a jpql query


How to get the number of records updated after executing a jpql query like

UPDATE Device d SET d.name =:Name WHERE d.locationId=:id

Solution

  • @Modifying  
    @Query("UPDATE Device d SET d.name =:Name WHERE d.locationId=:id")
    int updateDeviceName(@Param("Name") int Name,
            @Param("id") int id);
    

    The return type of the method is an Integer, which equals the number of affected rows, but one can set it to void if this is not desired or necessary. add @Modifying(clearAutomatically = true) to ensure that the EntityManager is getting cleaned up from the outdated entries to ensure the freshness of data.

    This ensures that the EntityManager is automatically cleared when the query has executed, ensuring that no entities are unsynchronized. This may be desirable in some situations, but it depends on the context in which the repository method is used, and thus you must be careful with this; it is easy to use such a method without noticing or remembering this side effect, and this could cause problems in your application. Hopefully unit tests would be in place to catch mistakes like this, but it may not be the case. So use this flag wisely.

    Referrence:-number of records update after executing an update query