I'm trying to have a H2 database setup on spring boot application startup. I have configured the database in application.properties:
spring.datasource.url = jdbc:h2:file:~/testdb
spring.datasource.username = sa
spring.datasource.password = sa
spring.datasource.driverClassName = org.h2.Driver
The Application.java file:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
CreateH2Database createH2Database = new CreateH2Database();
createH2Database.create();
}
}
CreateH2Database.java:
public class CreateH2Database {
private Logger log = Logger.getLogger(CreateH2Database.class);
@Autowired
protected JdbcTemplate jdbcTemplate;
public void create() {
log.info("Creating H2 Database");
createUsers();
}
private void createUsers() {
log.info("Creating users table");
jdbcTemplate.execute("create table if not exists users (id serial, first_name varchar(255), last_name varchar(255))");
String[] names = "John Woo;Jeff Dean;Josh Bloch;Josh Long".split(";");
for (String fullname : names) {
String[] name = fullname.split(" ");
log.info("Inserting user record for " + name[0] + " " + name[1] + "\n");
jdbcTemplate.update(
"INSERT INTO users(first_name,last_name) values(?,?)",
name[0], name[1]);
}
}
}
Once the application is started it should create the Users table if it doesn't already exist, and insert the users into the table. If the table does already exist, I don't want it to be modified.
- I get a
NullPointerExceptiononjdbcTemplate.execute. How can I get thejdbcTemplateinjected? All the example I've seen require the datasource to be created manually, and then the JdbcTemplate is created. However, the datasource in this example seems to be created based on the application.properties values. - Is this the correct approach to setup the database (i.e. calling a
CreateH2Databaseafter starting the SpringApplication)? Will this approach work if I want to run the application as a WAR on another application server?