Skip to content

DatabasePopulatorUtils uses non-transactional connection [SPR-9457] #14092

@spring-projects-issues

Description

@spring-projects-issues

Oliver Drotbohm opened SPR-9457 and commented

I've just been trying to populate a DataSource with some SQL in an @Before method in a transactional JUnit test. I've used the following code:

...
  @Autowired
  DataSource dataSource;
  
  @Before
  public void populateDatabase() throws SQLException {

    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("data.sql"));
    DatabasePopulatorUtils.execute(populator, dataSource);
  }
...

As methods annotated with @Before are expected to run within the transaction I wondered why the second test case always failed with an IntegrityViolationException inserting the same data twice as I would have expected the inserts contained in data.sql being rolled back.

Unfortunately DatasourcePopulatorUtils uses a plain dataSource.getConnection() call instead of DataSourceUtils.getConnection(dataSource) which would actually make sure we get the connection that's bound to the current transaction.

I now fell back to manually execute the populator as follows:

Connection connection = null;

try {
  connection = DataSourceUtils.getConnection(dataSource);
  populator.populate(connection);
} finally {
  if (connection != null) {
    DataSourceUtils.releaseConnection(connection, dataSource);
  }
}

which seems to be quite a step back from the approach above in terms of conciseness. Is there a reason DatabasePopulatorUtils does not aquire the connection through DataSourceUtils. If not I'd be happy to provide a pull request with the lookup fixed.


Affects: 3.1.1, 3.2 M1

Attachments:

Sub-tasks:

Referenced from: commits 0769d53, 67d5a12, 49c9a2a

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)type: bugA general bug

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions