Uploaded image for project: 'Spring Data JPA'
  1. Spring Data JPA
  2. DATAJPA-806

add flushAutomatically attribute to @Modifying annotation

    XMLWordPrintable

    Details

      Description

      @Modifying annotation has clearAutomatically attribute which defines whether it should clear the underlying persistence context after executing the modifying query.

      Code example:

      public interface EmailRepository extends JpaRepository<Email, Long> {
          @Transactional
          @Modifying(clearAutomatically = true)
          @Query("update Email e set e.active = false where e.active = true and e.expire <= NOW()")
          Integer deactivateByExpired();
      }
      

      When executing modifying queries with this attribute activated, it drops all non-flushed changes still pending in the EntityManager.

      To avoid this situation I had to implement a custom repository to manually execute the flush of the EntityManager, then the update query, and finally clear the underlying persistence context:

      public interface EmailRepository extends JpaRepository<Email, Long>, EmailRepositoryCustom {
      }
      
      public interface EmailRepositoryCustom {
          Integer deactivateByExpired();
      }
      
      public class EmailRepositoryImpl implements EmailRepositoryCustom {
          @PersistenceContext
          private EntityManager entityManager;
      
          @Transactional
          @Override
          public Integer deactivateByExpired() {
              String hsql = "update Email e set e.active = false where e.active = true and e.expire <= NOW()";
              Query query = entityManager.createQuery(hsql);
              entityManager.flush();
              Integer result = query.executeUpdate();
              entityManager.clear();
              return result;
          }
      }
      

      Is it possible to add a new attribute to @Modifying annotation called flushAutomatically to automatically flush all non-persisted changes to the underlying context before executing the modifying query?

        Attachments

          Activity

            People

            Assignee:
            olivergierke Oliver Drotbohm
            Reporter:
            ciri-cuervo Ciri
            Last updater:
            Spring Issues Spring Issues
            Votes:
            6 Vote for this issue
            Watchers:
            8 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: