Home > Software engineering >  SQL select in Java not returning any results from H2 database in unit test
SQL select in Java not returning any results from H2 database in unit test

Time:10-20

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:

  1. 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.
  2. You are using getAnyConnection from the multiTenantConnectionProvider. This might or might not be the same connection that is used by the EntityManager. If it isn't it will never see changes by the EntityManager if your database prevents dirty reads because a test rolls back transactions at the end of a test.
  • Related