private void closeConnection() { try { if (statement != null) statement.close(); if (connection != null) { JDBCExceptionReporter.logWarnings(connection.getWarnings()); connection.clearWarnings(); connectionProvider.closeConnection(connection); connectionProvider.close(); } } catch (Exception e) { System.err.println("Could not close connection"); e.printStackTrace(); } }
public void readFromDatabase(String catalog, String schema, Mapping mapping) { this.connectionProvider = settings.getConnectionProvider(); try { DatabaseCollector collector = readDatabaseSchema(catalog, schema); createPersistentClasses(collector, mapping); // move this to a different step! } catch (SQLException e) { throw settings.getSQLExceptionConverter().convert(e, "Reading from database", null); } finally { if (connectionProvider != null) connectionProvider.close(); } }
/** * Execute the schema updates * * @param script print all DDL to the console */ public void execute(boolean script, boolean doUpdate, File out) { log.info("Running hbm2ddl schema update"); Connection connection = null; Statement stmt = null; boolean autoCommitWasEnabled = true; FileWriter writer = null; if (script && out != null) { try { log.info("Creating filewriter to file : " + out.getAbsolutePath()); writer = new FileWriter(out); } catch (IOException e) { log.debug("IOException while creating filewriter"); log.debug(e); } } exceptions.clear(); try { DatabaseMetadata meta; try { log.info("fetching database metadata"); connection = connectionProvider.getConnection(); if (!connection.getAutoCommit()) { connection.commit(); connection.setAutoCommit(true); autoCommitWasEnabled = false; } meta = new DatabaseMetadata(connection, dialect); stmt = connection.createStatement(); } catch (SQLException sqle) { exceptions.add(sqle); log.error("could not get database metadata", sqle); throw sqle; } log.info("updating schema"); String[] createSQL = configuration.generateSchemaUpdateScript(dialect, meta); for (int j = 0; j < createSQL.length; j++) { final String sql = createSQL[j]; try { if (script) { System.out.println(sql); if (writer != null) { writer.write(sql + ";\n"); } } if (doUpdate) { log.debug(sql); stmt.executeUpdate(sql); } } catch (SQLException e) { exceptions.add(e); log.error("Unsuccessful: " + sql); log.error(e.getMessage()); } } if (writer != null) { writer.close(); } log.info("schema update complete"); } catch (Exception e) { exceptions.add(e); log.error("could not complete schema update", e); } finally { try { if (stmt != null) stmt.close(); if (!autoCommitWasEnabled) connection.setAutoCommit(false); if (connection != null) connection.close(); if (connectionProvider != null) connectionProvider.close(); } catch (Exception e) { exceptions.add(e); log.error("Error closing connection", e); } } }