Skip to content

add flushAutomatically attribute to @Modifying annotation [DATAJPA-806] #1167

@spring-projects-issues

Description

@spring-projects-issues

Ciri opened DATAJPA-806 and commented

@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?


Affects: 1.9 GA (Gosling)

Reference URL: http://stackoverflow.com/questions/32258857/spring-boot-data-jpa-modifying-update-query-refresh-persistence-context

Backported to: 2.0.4 (Kay SR4), 1.11.11 (Ingalls SR11)

6 votes, 8 watchers

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions