Why is it that after saving an Entity to the db, the select
SQL query returns 0 results?
I'm using Spring 2.6.2, Hibernate 5, H2 db in tests.
This is my test:
@Transactional
@Test
void test_OptimisticLockExceptionOnUpdate() throws SQLException {
String reportText = "Initial value: " new Date();
ReportDTO reportDTO = new ReportDTO();
reportDTO.setText(reportText);
// Save a report
reportDTO = reportService.submit(reportDTO);
Connection connection = multiTenantConnectionProvider.getAnyConnection();
String sql = "select * from PUBLIC.report";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String text = resultSet.getString("text");
System.out.println(text);
}
The method from my Service which persists a new Entity representing the DTO object:
@Transactional
public ReportDTO submit(ReportDTO input) {
ReportEntity reportEntity = new ReportEntity();
reportEntity.setText(input.getText());
reportEntity = reportRepository.save(reportEntity);
input.setId(reportEntity.getId());
input.setVersion(reportEntity.getVersion());
return input;
}
CodePudding user response:
There are two possible explanations:
- Since your test is annotated with
@Transactional
everything is running in a single transaction. JPA does not save your entities when you ask it it to do it. Instead it just tracks them to save them to the database ones it becomes necessary, which often only is at the end of the transaction. It also flushes changes to the database before queries are executed, but only if they are executed via JPA, otherwise it wouldn't know about them. - You are using
getAnyConnection
from themultiTenantConnectionProvider
. This might or might not be the same connection that is used by theEntityManager
. If it isn't it will never see changes by theEntityManager
if your database prevents dirty reads because a test rolls back transactions at the end of a test.