The CategoryRepository
is defined like this:
public interface CategoryRepository extends JpaRepository<Category, Long>{
@Transactional
@Query("select c from Category c where name = :name")
Optional<Category> findByName(String name);
}
Here is the test case:
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CategoryRepositoryTests {
@Autowired
private CategoryRepository categoryRepository;
@Test
@Transactional
public void testCaching(){
categoryRepository.findByName("cat1");
categoryRepository.findByName("cat1");
}
}
In db there is always a category named cat1
. My expectation is after the 1st statement
categoryRepository.findByName("cat1");
Category
object should be in persistence context and thus the second call shouldn’t query the db again. This is not happening. The second call hits the db again. Here are the logs.