AD

Hibernate in the source code analysis tools SchemaUpdate

/ / Export the target application database
package org.hibernate.tool.hbm2ddl;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.dialect.Dialect;
import org.hibernate.jdbc.util.FormatStyle;
import org.hibernate.jdbc.util.Formatter;
import org.hibernate.jdbc.util.SQLStatementLogger;
import org.hibernate.util.PropertiesHelper;
import org.hibernate.util.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/ **
* A commandline tool to update a database schema. May also be called from
* Inside an application.
*
* @ Author Christoph Sturm
* /
public class SchemaUpdate (

private static final Logger log = LoggerFactory.getLogger (SchemaUpdate.class);
private ConnectionHelper connectionHelper;
private Configuration configuration;
private Dialect dialect;
private List exceptions;
private boolean haltOnError = false;
private boolean format = true;
private String outputFile = null;
private String delimiter;
private Formatter formatter;
private SQLStatementLogger sqlStatementLogger;

public SchemaUpdate (Configuration cfg) throws HibernateException (
this (cfg, cfg.getProperties ());
)

public SchemaUpdate (Configuration cfg, Properties connectionProperties) throws HibernateException (
this.configuration = cfg;
dialect = Dialect.getDialect (connectionProperties);
Properties props = new Properties ();
props.putAll (dialect.getDefaultProperties ());
props.putAll (connectionProperties);
connectionHelper = new ManagedProviderConnectionHelper (props);
exceptions = new ArrayList ();
formatter = (PropertiesHelper.getBoolean (Environment.FORMAT_SQL, props)? FormatStyle.DDL: FormatStyle.NONE). getFormatter ();
)

public SchemaUpdate (Configuration cfg, Settings settings) throws HibernateException (
this.configuration = cfg;
dialect = settings.getDialect ();
connectionHelper = new SuppliedConnectionProviderConnectionHelper (
settings.getConnectionProvider ()
);
exceptions = new ArrayList ();
sqlStatementLogger = settings.getSqlStatementLogger ();
formatter = (sqlStatementLogger.isFormatSql ()? FormatStyle.DDL: FormatStyle.NONE). getFormatter ();
)

public static void main (String [] args) (
try (
Configuration cfg = new Configuration ();

boolean script = true;
/ / If true then execute db updates, otherwise just generate and display updates
boolean doUpdate = true;
String propFile = null;

for (int i = 0; i <args.length; i + +) (
if (args [i]. startsWith ( "-")) (
if (args [i]. equals ( "- quiet")) (
script = false;
)
else if (args [i]. startsWith ( "- properties =")) (
propFile = args [i]. substring (13);
)
else if (args [i]. startsWith ( "- config =")) (
cfg.configure (args [i]. substring (9));
)
else if (args [i]. startsWith ( "- text")) (
doUpdate = false;
)
else if (args [i]. startsWith ( "- naming =")) (
cfg.setNamingStrategy (
(NamingStrategy) ReflectHelper.classForName (args [i]. Substring (9)). NewInstance ()
);
)
)
else (
cfg.addFile (args [i]);
)

)

if (propFile! = null) (
Properties props = new Properties ();
props.putAll (cfg.getProperties ());
props.load (new FileInputStream (propFile));
cfg.setProperties (props);
)

new SchemaUpdate (cfg). execute (script, doUpdate);
)
catch (Exception e) (
log.error ( "Error running schema update", e);
e.printStackTrace ();
)
)

/ **
* Execute the schema updates
*
* @ Param script print all DDL to the console
* /
public void execute (boolean script, boolean doUpdate) (

log** ( "Running hbm2ddl schema update");

Connection connection = null;
Statement stmt = null;
Writer outputFileWriter = null;

exceptions.clear ();

try (

DatabaseMetadata meta;
try (
log** ( "fetching database metadata");
connectionHelper.prepare (true);
connection = connectionHelper.getConnection ();
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** ( "updating schema");

if (outputFile! = null) (
log** ( "writing generated schema to file:" + outputFile);
outputFileWriter = new FileWriter (outputFile);
)

String [] createSQL = configuration.generateSchemaUpdateScript (dialect, meta);
for (int j = 0; j <createSQL.length; j + +) (

final String sql = createSQL [j];
String formatted = formatter.format (sql);
try (
if (delimiter! = null) (
formatted + = delimiter;
)
if (script) (
System.out.println (formatted);
)
if (outputFile! = null) (
outputFileWriter.write (formatted + "\ n");
)
if (doUpdate) (
log.debug (sql);
stmt.executeUpdate (formatted);
)
)
catch (SQLException e) (
if (haltOnError) (
throw new JDBCException ( "Error during DDL export", e);
)
exceptions.add (e);
log.error ( "Unsuccessful:" + sql);
log.error (e.getMessage ());
)
)

log** ( "schema update complete");

)
catch (Exception e) (
exceptions.add (e);
log.error ( "could not complete schema update", e);
)
finally (

try (
if (stmt! = null) (
stmt.close ();
)
connectionHelper.release ();
)
catch (Exception e) (
exceptions.add (e);
log.error ( "Error closing connection", e);
)
try (
if (outputFileWriter! = null) (
outputFileWriter.close ();
)
)
catch (Exception e) (
exceptions.add (e);
log.error ( "Error closing connection", e);
)
)
)

/ **
* Returns a List of all Exceptions which occured during the export.
*
* @ Return A List containig the Exceptions occured during the export
* /
public List getExceptions () (
return exceptions;
)

public void setHaltOnError (boolean haltOnError) (
this.haltOnError = haltOnError;
)

public void setFormat (boolean format) (
this.formatter = (format? FormatStyle.DDL: FormatStyle.NONE). getFormatter ();
)

public void setOutputFile (String outputFile) (
this.outputFile = outputFile;
)

public void setDelimiter (String delimiter) (
this.delimiter = delimiter;
)

)

Provision of appropriate methods to achieve the functions of the corresponding

Test code

package org.hibernate.test.schemaupdate;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.hibernate.cfg.Configuration;
import org.hibernate.junit.UnitTestCase;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

/ **
* * /
public class MigrationTest extends UnitTestCase (

public MigrationTest (String str) (
super (str);
)

public static Test suite () (
return new TestSuite (MigrationTest.class);
)

public void testSimpleColumnAddition () (
String resource1 = "org/hibernate/test/schemaupdate/1_Version.hbm.xml";
String resource2 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml";

Configuration v1cfg = new Configuration ();
v1cfg.addResource (resource1);
new SchemaExport (v1cfg). execute (false, true, true, false);

SchemaUpdate v1schemaUpdate = new SchemaUpdate (v1cfg);
v1schemaUpdate.execute (true, true);

assertEquals (0, v1schemaUpdate.getExceptions (). size ());

Configuration v2cfg = new Configuration ();
v2cfg.addResource (resource2);

SchemaUpdate v2schemaUpdate = new SchemaUpdate (v2cfg);
v2schemaUpdate.execute (true, true);
assertEquals (0, v2schemaUpdate.getExceptions (). size ());

)

)

标签: import java, java util, java sql, import org, package org, sql connection, sqlexception, dialect, sql statement, fileinputstream, arraylist, source code analysis, database schema, analysis tools, statement import, database package, target application, commandline tool, filewriter, application database
分类: Java
时间: 2009-09-18

相关文章

  1. (R) linux source code analysis tools, and read more

    Reprinted from: http://hi.baidu.com/likeadream/blog/item/7664bb349daf0049241f144c.html Reading tool for Window ...
  2. 11 used for optimization. 'S Java source code analysis tools (forward)

    This article will provide some tools to help you optimize the code and check the source code for potential pro ...
  3. 11 used for optimization. 'S Java source code analysis tools

    This article will provide some tools to help you optimize the code and check the source code for potential pro ...
  4. Hibernate in SchemaExport, SchemaUpdate source code analysis tools

    package org.hibernate.tool.hbm2ddl; import java.io.BufferedReader; import java.io.File; import java.io.FileInp ...
  5. (R) linux source code analysis and comparative reading tools

    Reprinted from: http://hi.baidu.com/likeadream/blog/item/7664bb349daf0049241f144c.html Windows source code und ...
  6. Spring source code analysis (8): Spring-driven implementation of Hibernate

    O / R tool came to simplify the complex information of many persistent development. Spring application develop ...
  7. Tomcat 5.5.26 source code analysis - start the process (2)

    init method Catalina_Home and Catalina_Base Initialize the system class loader Tomcat's class loader system in ...
  8. Mysql source code analysis series

    Mysql source code analysis series (2): the source code structure Mysql source code include the client code, se ...
  9. Heritrix source code analysis (9) Heritrix secondary to Heritrix crawl crawl and how to capture the URL you do not want

    I said before Heritrix crawl in a basis (here assumed to be A) to crawl, because Heritrix on each URL will hav ...
  10. iBATIS source code analysis framework

    iBATIS source code analysis framework Basic Information Of: any steel Publisher: Electronic Industry Press ISB ...
  11. One of the server source code analysis Tracker: Overview

    One of the server source code analysis Tracker: Overview Of: Ma Ying-jeou Date :2004-5-29 BT download tracker ...
  12. Ruby On Rails-2.0.2 source code analysis (1)-Rails Start

    Preface This article is for Ruby On Rails 2.0.2 source code analysis, learning and research. The tools used Ne ...
  13. Heritrix source code analysis (nine) Heritrix crawl and how to get the second you do not want to crawl Heritrix crawl URL

    http://guoyunsky.javaeye.com/blog/644396 I said before Heritrix basis at a crawl (here assumed to be A) contin ...
  14. (Transfer) MapReduce source code analysis summary

    Original Address: http://www.cnblogs.com/end/archive/2011/04/26/2029499.html Transferred by Note: The summary ...
  15. Struts2 source code analysis - Request Processing

    Struts2 source code analysis - Request Processing http://www.javaeye.com/topic/450979
  16. TOMCAT source code analysis (Message Processing)

    TOMCAT source code analysis (Message Processing) http://yuleihome.javaeye.com/blog/562244
  17. openjdk source code analysis --- the loading of class analysis

    openjdk source code analysis --- the loading of class analysis (* env) -> FindClass implementation, to find ...
  18. ThreadLocal Source Code Analysis

    Had previously been associated ThreadLocal reproduced the article, but it has been in a confused state, when t ...
  19. Spring source code analysis (4): Spring MVC

    The following Spring MVC framework of the code we analyzed, for webApplicationContext correlation analysis can ...