I am using Spring JdbcTemplate
with the DAO pattern to access a database. Instead of creating the database tables manually, I am looking for a way to generate the tables in the DAO layer.
I understand that I can use the JdbcTemplate
to execute statements, I am only looking for the right place to do it.
Is there a best practice for that?
There are four steps for creating a table using JDBC API. Open connection to the database. Create a statement object to perform a create table query. Execute the executeUpdate() method of statement object to submit a query to database.
The Spring JDBC Template has the following advantages compared with standard JDBC. The Spring JDBC template allows to clean-up the resources automatically, e.g. release the database connections. The Spring JDBC template converts the standard JDBC SQLExceptions into RuntimeExceptions.
Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.
First, install some DDL by using the execute method of JdbcTemplate . Second, take a list of strings and, by using Java 8 streams, split them into firstname/lastname pairs in a Java array. Then install some records in your newly created table by using the batchUpdate method of JdbcTemplate .
You can use the execute(String) method:
public void execute(String sql) throws DataAccessException
Issue a single SQL execute, typically a DDL statement.
Specified by: execute in interface JdbcOperationsParameters: sql - static SQL to execute
Throws: DataAccessException - if there is any problem
However as beny23 mentions I would be suspicious of an actual need to do this programatically in a live application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With