OK, I understand that there currently is no such function for hbm2ddl.auto.
max wrote:
so how would you decide that the database is "not there" ?
Hibernate could decide this by asking the dbms if the database exists. See example code below.
max wrote:
i think you are better of writing a custom initialization code that uses schemaexport to do what you want based on your definition of "not there"
In most cases, if the database does not exist, I just want Hibernate to create it and the schema to be exported, just like with
<property name="hbm2ddl.auto">create</property>
for example
<property name="hbm2ddl.auto">create-if-not-exists</property>
All the pieces are already there (except, perhaps, db detection), so Hibernate could save the users from manually writing custom initialization code if the database just should be created without further ceremony.
This would be very useful. I have googled myself blue to find out if/how this can be done, and found no answer - but a lot of other folks with the same question.
Here's the example code. It does a little more than just create the database, but you'll see the interesting part.
Code:
private static Connection createConnection()
throws SystemException
{
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String jdbc_url = "jdbc:mysql://localhost/?user=fred";
Connection conn = DriverManager.getConnection(jdbc_url);
// Does dbName exist?
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getCatalogs(); // closed with stmt.close()
boolean found = false;
while (rs.next()) {
String catalog = rs.getString(1);
if (catalog.equals(dbName)) {
found = true;
}
}
// Nuts. Create it!
if (!found) {
stmt = conn.createStatement();
stmt.execute("CREATE DATABASE " + dbName);
stmt.close();
conn.setCatalog(dbName);
stmt = conn.createStatement();
String sql =
"CREATE TABLE " + tableName +
" (user_name VARCHAR(255) NOT NULL, " +
" setting_key VARCHAR(255) NOT NULL, " +
" setting_value VARCHAR(255), " +
" PRIMARY KEY k1 (user_name, setting_key) " +
" ) TYPE=InnoDB;";
stmt.execute(sql);
stmt.close();
}
conn.setCatalog(dbName);
return conn;
}
catch (ClassNotFoundException e) {
throw new SystemException("No database driver", e);
}
catch (SQLException e) {
throw new SystemException("SQL problem", e);
}
finally {
try {
if (stmt != null)
stmt.close();
}
catch (SQLException e) {}
}
}