Skip to content

Commit

Permalink
Enforce modifying methods are annotated with @transactional
Browse files Browse the repository at this point in the history
  • Loading branch information
quaff committed Oct 13, 2023
1 parent 35dc371 commit e5579c0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ public boolean exists(Specification<T> spec) {
}

@Override
@Transactional
public long delete(Specification<T> spec) {

CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
package org.springframework.data.jpa.repository.support;

import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
Expand All @@ -31,8 +33,11 @@
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -45,6 +50,7 @@
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

/**
* Unit tests for {@link SimpleJpaRepository}.
Expand All @@ -54,6 +60,7 @@
* @author Mark Paluch
* @author Jens Schauder
* @author Greg Turnquist
* @author Yanming Zhou
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
Expand Down Expand Up @@ -216,4 +223,20 @@ void applyQueryHintsToCountQueriesForSpecificationPageables() {

verify(metadata).getQueryHintsForCount();
}

@Test // GH-3188
void checkTransactionalAnnotation() {
Stream.of(SimpleJpaRepository.class.getDeclaredMethods()).filter(method -> Modifier.isPublic(method.getModifiers()) &&
(method.getName().startsWith("delete") || method.getName().startsWith("save"))).forEach(
method -> {
if (!method.isAnnotationPresent(Transactional.class)) {
fail("Method [" + method + "] should be annotated with @Transactional");
}
Transactional transactional = method.getAnnotation(Transactional.class);
if (transactional.readOnly()) {
fail("Method [" + method + "] should not be annotated with @Transactional(readOnly = true)");
}
}
);
}
}

0 comments on commit e5579c0

Please sign in to comment.