-
Notifications
You must be signed in to change notification settings - Fork 38.6k
Description
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:
- mylyn-context.zip (6.04 kB)
Sub-tasks:
- Backport "DatabasePopulatorUtils uses non-transactional connection" [SPR-9465] #14100 Backport "DatabasePopulatorUtils uses non-transactional connection"