|
In the TestApplication class, I save a JPA entity 3 times using a Spring Data JPA repository backed by Hibernate configured with a second level cache.
On the first save, a SQL INSERT is issued by Hibernate. On the second save, two SQL queries are issued by Hibernate : a SELECT and an UPDATE. Finally, on the third save, only a SQL UPDATE is issued by Hibernate.
Why do I have the SELECT query during the second save? The entity should already be in the second level cache after the first save and the second save should behave like the third save.
Test.java:
@Entity
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Test {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String value;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
TestRepository.java:
public interface TestRepository extends JpaRepository<Test, Long> {
}
TestApplication.java:
@SpringBootApplication
public class TestApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(TestApplication.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(TestApplication.class, args);
TestRepository testRepository = configurableApplicationContext.getBean(TestRepository.class);
Test test = new Test();
test.setValue("test1");
LOGGER.info("Save 1");
testRepository.save(test);
test.setValue("test2");
LOGGER.info("Save 2");
testRepository.save(test);
test.setValue("test3");
LOGGER.info("Save 3");
testRepository.save(test);
}
}
application.properties:
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
Run log:
|