I am trying to run a spring boot application with embedded db. During beans initialization (for some reason?), My script table creation is called twice, and the second call fails with a "table already exists" error. Below is my code, which could be a problem.
@Configuration
public class AppConfig {
private static final Logger LOG = LoggerFactory.getLogger(AppConfig.class);
private static EmbeddedDatabase dataSource;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new DbPlaceholderConfigurer(dataSource());
}
@Bean
public static EmbeddedDatabase dataSource() {
if(dataSource == null) {
EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
databaseBuilder.addScript("classpath:schema.sql");
databaseBuilder.setType(EmbeddedDatabaseType.H2);
EmbeddedDatabase build = databaseBuilder.build();
initPopulate(build);
dataSource = build;
}
return dataSource;
}
private static void initPopulate(EmbeddedDatabase embeddedDatabase) {
try {
Connection connection = embeddedDatabase.getConnection();
PreparedStatement prepareStatement;
prepareStatement = connection.prepareStatement("INSERT INTO Settings VALUES (?,?,?)");
prepareStatement.setInt(1, 1);
prepareStatement.setString(2, "testKey");
prepareStatement.setString(3, "testVal");
prepareStatement.executeUpdate();
connection.close();
} catch (SQLException e) {
LOG.error("Error ", e);
}
}
}
Error log below:
Caused by: org.h2.jdbc.JdbcSQLException: Table "SETTINGS" already exists; SQL statement:
CREATE TABLE Settings( id INT PRIMARY KEY, testKey VARCHAR(100), testValue VARCHAR(100) ) [42101-192]
Note. I can successfully download my application by setting the following property, but I'm really curious why spring calls the script table twice.
spring.datasource.continue-on-error=true
Note2: Creating a script table (schema.sql) looks like this:
create table contacts (
id identity,
firstname varChar(30) not null,
lastName varChar(30) not null,
phoneNumber varChar(20),
emailAddress varChar(50)
);
source
share