Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 540
Jesalcv Avatar asked Nov 26 '15 10:11

Jesalcv


People also ask

Which of the following methods is used to execute a select JPQL query?

Query createQuery(String name) - The createQuery() method of EntityManager interface is used to create an instance of Query interface for executing JPQL statement.

Which methods should be used for pagination with JPQL?

For all JPA query objects (except for native SQL queries), you would use pagination through the setMaxResults(int) and setFirstResult(int) methods.

Which annotation is used for binding JPQL query?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file.

Which annotation is used for binding JPQL query with method in spring data A?

Creating a JPQL query with Spring Data JPA's @Query annotation is pretty straightforward. You need to annotate a method on your repository interface with the @Query annotation and provide a String with the JPQL query statement.


2 Answers

@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

like image 160
Jesalcv Avatar answered Jan 04 '23 04:01

Jesalcv


You can use executeUpdate() method to get count like this:

Query query = em.createQuery(
  "UPDATE Device d SET d.name =:Name WHERE d.locationId=:id");
int updateCount = em.executeUpdate();
like image 26
chirag.sweng Avatar answered Jan 04 '23 04:01

chirag.sweng