`
longgangbai
  • 浏览: 7357145 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Hibernate 中的SchemaExport,SchemaUpdate工具源码分析使用

阅读更多


package org.hibernate.tool.hbm2ddl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.ConfigHelper;
import org.hibernate.util.JDBCExceptionReporter;
import org.hibernate.util.PropertiesHelper;
import org.hibernate.util.ReflectHelper;

/**
 * 命令行将同居将导入表的schema到数据库的类对象
 *
 * @author Daniel Bradby
 * @author Gavin King
 */
public class SchemaExport {

 private static final Logger log = LoggerFactory.getLogger( SchemaExport.class );

 private ConnectionHelper connectionHelper;
 private String[] dropSQL;
 private String[] createSQL;
 private String outputFile = null;
 private String importFile = "/import.sql";
 private Dialect dialect;
 private String delimiter;
 private final List exceptions = new ArrayList();
 private boolean haltOnError = false;
 private Formatter formatter;
 private SQLStatementLogger sqlStatementLogger;

 /**
  * Create a schema exporter for the given Configuration
  * 创建Schema导出对象的应用
  * @param cfg The configuration from which to build a schema export.
  * @throws HibernateException Indicates problem preparing for schema export.
  */
 public SchemaExport(Configuration cfg) throws HibernateException {
  this( cfg, cfg.getProperties() );
 }

 /**
  * Create a schema exporter for the given Configuration and given settings
  *
  * @param cfg The configuration from which to build a schema export.
  * @param settings The 'parsed' settings.
  * @throws HibernateException Indicates problem preparing for schema export.
  */
 public SchemaExport(Configuration cfg, Settings settings) throws HibernateException {
  dialect = settings.getDialect();
  connectionHelper = new SuppliedConnectionProviderConnectionHelper( settings.getConnectionProvider() );
  dropSQL = cfg.generateDropSchemaScript( dialect );
  createSQL = cfg.generateSchemaCreationScript( dialect );
  sqlStatementLogger = settings.getSqlStatementLogger();
  formatter = ( sqlStatementLogger.isFormatSql() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
 }

 /**
  * Create a schema exporter for the given Configuration, with the given
  * database connection properties.
  *
  * @param cfg The configuration from which to build a schema export.
  * @param properties The properties from which to configure connectivity etc.
  * @throws HibernateException Indicates problem preparing for schema export.
  *
  * @deprecated properties may be specified via the Configuration object
  */
 public SchemaExport(Configuration cfg, Properties properties) throws HibernateException {
  dialect = Dialect.getDialect( properties );

  Properties props = new Properties();
  props.putAll( dialect.getDefaultProperties() );
  props.putAll( properties );

  connectionHelper = new ManagedProviderConnectionHelper( props );
  dropSQL = cfg.generateDropSchemaScript( dialect );
  createSQL = cfg.generateSchemaCreationScript( dialect );

  formatter = ( PropertiesHelper.getBoolean( Environment.FORMAT_SQL, props ) ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
 }

 /**
  * Create a schema exporter for the given Configuration, using the supplied connection for connectivity.
  *
  * @param cfg The configuration to use.
  * @param connection The JDBC connection to use.
  * @throws HibernateException Indicates problem preparing for schema export.
  */
 public SchemaExport(Configuration cfg, Connection connection) throws HibernateException {
  this.connectionHelper = new SuppliedConnectionHelper( connection );
  dialect = Dialect.getDialect( cfg.getProperties() );
  dropSQL = cfg.generateDropSchemaScript( dialect );
  createSQL = cfg.generateSchemaCreationScript( dialect );
  formatter = ( PropertiesHelper.getBoolean( Environment.FORMAT_SQL, cfg.getProperties() ) ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
 }

 /**
  * For generating a export script file, this is the file which will be written.
  *  设置输出文件位置
  * @param filename The name of the file to which to write the export script.
  * @return this
  */
 public SchemaExport setOutputFile(String filename) {
  outputFile = filename;
  return this;
 }

 /**
  * An import file, containing raw SQL statements to be executed.
  *
  * @param filename The import file name.
  * @return this
  */
 public SchemaExport setImportFile(String filename) {
  importFile = filename;
  return this;
 }

 /**
  * Set the end of statement delimiter
  *
  * @param delimiter The delimiter
  * @return this
  */
 public SchemaExport setDelimiter(String delimiter) {
  this.delimiter = delimiter;
  return this;
 }

 /**
  * Should we format the sql strings?  是否需要格式化的代码
  *
  * @param format Should we format SQL strings
  * @return this
  */
 public SchemaExport setFormat(boolean format) {
  this.formatter = ( format ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
  return this;
 }

 /**
  * Should we stop once an error occurs?
  *
  * @param haltOnError True if export should stop after error.
  * @return this
  */
 public SchemaExport setHaltOnError(boolean haltOnError) {
  this.haltOnError = haltOnError;
  return this;
 }

 /**
  * Run the schema creation script.  运行创建代码的脚本的应用
  *
  * @param script print the DDL to the console
  * @param export export the script to the database
  */
 public void create(boolean script, boolean export) {
  execute( script, export, false, false );
 }

 /**
  * Run the drop schema script.运行删除的代码的脚本的应用
  *
  * @param script print the DDL to the console
  * @param export export the script to the database
  */
 public void drop(boolean script, boolean export) {
  execute( script, export, true, false );
 }

//执行相关的脚本信息

 public void execute(boolean script, boolean export, boolean justDrop, boolean justCreate) {

  log.info( "Running hbm2ddl schema export" );

  Connection connection = null;
  Writer outputFileWriter = null;
  Reader importFileReader = null;
  Statement statement = null;

  exceptions.clear();

  try {

   try {
    InputStream stream = ConfigHelper.getResourceAsStream( importFile );
    importFileReader = new InputStreamReader( stream );
   }
   catch ( HibernateException e ) {
    log.debug( "import file not found: " + importFile );
   }

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

   if ( export ) {
    log.info( "exporting generated schema to database" );
    connectionHelper.prepare( true );
    connection = connectionHelper.getConnection();
    statement = connection.createStatement();
   }

   if ( !justCreate ) {
    drop( script, export, outputFileWriter, statement );
   }

   if ( !justDrop ) {
    create( script, export, outputFileWriter, statement );
    if ( export && importFileReader != null ) {
     importScript( importFileReader, statement );
    }
   }

   log.info( "schema export complete" );

  }

  catch ( Exception e ) {
   exceptions.add( e );
   log.error( "schema export unsuccessful", e );
  }

  finally {

   try {
    if ( statement != null ) {
     statement.close();
    }
    if ( connection != null ) {
     connectionHelper.release();
    }
   }
   catch ( Exception e ) {
    exceptions.add( e );
    log.error( "Could not close connection", e );
   }

   try {
    if ( outputFileWriter != null ) {
     outputFileWriter.close();
    }
    if ( importFileReader != null ) {
     importFileReader.close();
    }
   }
   catch ( IOException ioe ) {
    exceptions.add( ioe );
    log.error( "Error closing output file: " + outputFile, ioe );
   }

  }
 }

 private void importScript(Reader importFileReader, Statement statement)
   throws IOException {
  log.info( "Executing import script: " + importFile );
  BufferedReader reader = new BufferedReader( importFileReader );
  long lineNo = 0;
  for ( String sql = reader.readLine(); sql != null; sql = reader.readLine() ) {
   try {
    lineNo++;
    String trimmedSql = sql.trim();
    if ( trimmedSql.length() == 0 ||
         trimmedSql.startsWith( "--" ) ||
         trimmedSql.startsWith( "//" ) ||
         trimmedSql.startsWith( "/*" ) ) {
     continue;
    }
    else {
     if ( trimmedSql.endsWith( ";" ) ) {
      trimmedSql = trimmedSql.substring( 0, trimmedSql.length() - 1 );
     }
     log.debug( trimmedSql );
     statement.execute( trimmedSql );
    }
   }
   catch ( SQLException e ) {
    throw new JDBCException( "Error during import script execution at line " + lineNo, e );
   }
  }
 }

 private void create(boolean script, boolean export, Writer fileOutput, Statement statement)
   throws IOException {
  for ( int j = 0; j < createSQL.length; j++ ) {
   try {
    execute( script, export, fileOutput, statement, createSQL[j] );
   }
   catch ( SQLException e ) {
    if ( haltOnError ) {
     throw new JDBCException( "Error during DDL export", e );
    }
    exceptions.add( e );
    log.error( "Unsuccessful: " + createSQL[j] );
    log.error( e.getMessage() );
   }
  }
 }

 private void drop(boolean script, boolean export, Writer fileOutput, Statement statement)
   throws IOException {
  for ( int i = 0; i < dropSQL.length; i++ ) {
   try {
    execute( script, export, fileOutput, statement, dropSQL[i] );
   }
   catch ( SQLException e ) {
    exceptions.add( e );
    log.debug( "Unsuccessful: " + dropSQL[i] );
    log.debug( e.getMessage() );
   }
  }
 }

 private void execute(boolean script, boolean export, Writer fileOutput, Statement statement, final String sql)
   throws IOException, SQLException {
  String formatted = formatter.format( sql );
  if ( delimiter != null ) {
   formatted += delimiter;
  }
  if ( script ) {
   System.out.println( formatted );
  }
  log.debug( formatted );
  if ( outputFile != null ) {
   fileOutput.write( formatted + "\n" );
  }
  if ( export ) {

   statement.executeUpdate( sql );
   try {
    SQLWarning warnings = statement.getWarnings();
    if ( warnings != null) {
     JDBCExceptionReporter.logAndClearWarnings( connectionHelper.getConnection() );
    }
   }
   catch( SQLException sqle ) {
    log.warn( "unable to log SQLWarnings : " + sqle );
   }
  }

  
 }

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

   boolean script = true;
   boolean drop = false;
   boolean create = false;
   boolean halt = false;
   boolean export = true;
   String outFile = null;
   String importFile = "/import.sql";
   String propFile = null;
   boolean format = false;
   String delim = null;

   for ( int i = 0; i < args.length; i++ ) {
    if ( args[i].startsWith( "--" ) ) {
     if ( args[i].equals( "--quiet" ) ) {
      script = false;
     }
     else if ( args[i].equals( "--drop" ) ) {
      drop = true;
     }
     else if ( args[i].equals( "--create" ) ) {
      create = true;
     }
     else if ( args[i].equals( "--haltonerror" ) ) {
      halt = true;
     }
     else if ( args[i].equals( "--text" ) ) {
      export = false;
     }
     else if ( args[i].startsWith( "--output=" ) ) {
      outFile = args[i].substring( 9 );
     }
     else if ( args[i].startsWith( "--import=" ) ) {
      importFile = args[i].substring( 9 );
     }
     else if ( args[i].startsWith( "--properties=" ) ) {
      propFile = args[i].substring( 13 );
     }
     else if ( args[i].equals( "--format" ) ) {
      format = true;
     }
     else if ( args[i].startsWith( "--delimiter=" ) ) {
      delim = args[i].substring( 12 );
     }
     else if ( args[i].startsWith( "--config=" ) ) {
      cfg.configure( args[i].substring( 9 ) );
     }
     else if ( args[i].startsWith( "--naming=" ) ) {
      cfg.setNamingStrategy(
        ( NamingStrategy ) ReflectHelper.classForName( args[i].substring( 9 ) )
          .newInstance()
      );
     }
    }
    else {
     String filename = args[i];
     if ( filename.endsWith( ".jar" ) ) {
      cfg.addJar( new File( filename ) );
     }
     else {
      cfg.addFile( filename );
     }
    }

   }

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

   SchemaExport se = new SchemaExport( cfg )
     .setHaltOnError( halt )
     .setOutputFile( outFile )
     .setImportFile( importFile )
     .setDelimiter( delim );
   if ( format ) {
    se.setFormat( true );
   }
   se.execute( script, export, drop, create );

  }
  catch ( Exception e ) {
   log.error( "Error creating schema ", e );
   e.printStackTrace();
  }
 }

 /**
  * 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;
 }
}
调用相应的防范实现相应的业务逻辑在应用程序库中

分享到:
评论

相关推荐

    利用hibernate中的SchemaExport生成数据表

    总结起来,使用Hibernate的`SchemaExport`工具进行数据库表的生成,是ORM理念在实际开发中的体现,它帮助我们更好地遵循面向对象的设计原则,简化了开发流程。通过定义对象和它们的映射关系,我们可以让Hibernate...

    最新hibernate版本5.2.11final

    最新hibernate 版本5.2.11.final--最新hibe--最新hibernate 版本5.2.11.finalrnate 版本5.2.11.final--最新hibernate 版本5.2.11.final

    hibernate根据字段生成数据库表

    - 给定的示例代码中,可以看到 `SchemaExport` 类的使用方式。 #### 三、核心代码解析 1. **创建 Configuration 对象**: ```java config = new Configuration().configure(new File("src/hibernate.cfg.xml"))...

    hibernate-extensions和Middlegen-Hibernate

    其中,最具吸引力的是它的`SchemaExport`和`SchemaUpdate`工具,这两个工具能够根据配置的实体类自动生成数据库的DDL脚本,或者直接在现有的数据库上更新表结构。此外,hibernate-extensions还支持动态代理,允许...

    Hibernate+中文文档

    目录 前言 1. 翻译说明 2. 版权声明 1. Hibernate入门 1.1. 前言 1.2. 第一部分 - 第一个Hibernate应用程序 1.2.1. 第一个class ...20.4. SchemaUpdate命令行选项 20.5. SchemaValidator命令行参数

    hibernate的映射表生成器

    Hibernate是一个开源的对象关系映射(ORM)框架,它允许Java开发者在数据库操作中使用面向对象的方式,极大地简化了数据库编程。标题中的“hibernate的映射表生成器”是一个图形用户界面(GUI)工具,专门设计用于...

    hibernate3.2中文文档(chm格式)

    HIBERNATE - 符合Java习惯的关系数据库持久化 Hibernate参考文档 3.2 -------------------------------------------------------------------------------- 目录 前言 1. 翻译说明 2. 版权声明 1. Hibernate...

    hibernate3中文手册

    15. **Hibernate工具**:介绍Hibernate的SchemaExport工具用于生成数据库结构,以及Enhancer工具对实体类进行增强。 16. **Hibernate与其他技术的整合**:如Spring框架的整合,以及与MyBatis、JPA等其他ORM框架的...

    Hibernate 映射文件自动生成

    5. **更新数据库表**:在生成映射文件后,还可以结合Hibernate的SchemaExport工具生成或更新数据库表结构。 这样的自动化过程可以帮助开发者节省大量时间,并且减少人为错误。在实际开发中,例如使用Eclipse或...

    Ant打包 Hibernate配置 实例

    2. **生成Hibernate配置文件**:使用Hibernate的SchemaExport工具,我们可以根据实体类生成数据库表结构,或者根据现有数据库结构生成映射文件。 3. **编译源代码**:确保所有Hibernate相关的类被正确编译。 4. **...

    hibernate反向生成数据库程序

    总的来说,这段代码演示了如何使用Hibernate框架的`SchemaExport`工具来反向生成数据库结构。在实际项目中,开发者可能会进一步利用Hibernate的逆向工程功能,自动生成实体类和映射文件,以便更方便地进行数据库操作...

    根据hibernate配置文件生成数据库.zip

    1. **使用Hibernate的工具hbm2ddl根据你的对象建立数据库SchemaExport.doc** Hibernate的hbm2ddl工具能够根据实体类(即你的对象)和对应的映射文件(.hbm.xml)自动生成数据库模式。SchemaExport是这个工具的一个...

    改AHibernate 实现数据库 自动新增表参数

    因此,建议在生产环境中使用单独的数据库迁移工具,如Flyway或 Liquibase,来管理数据库版本。 总的来说,通过扩展和定制Hibernate的行为,我们可以实现自动在数据库表中新增包含version字段的参数,从而更好地支持...

    hibernate映射文件生成数据库

    4. 使用工具或API生成数据库:有了映射文件,你可以使用Hibernate的`SchemaExport`工具或者编程方式执行`sessionFactory.createSchema()`方法来根据映射文件生成数据库表。这将在数据库中创建对应的表结构。 三、...

    HibernateAPI中文版.chm

    HIBERNATE - 符合Java习惯的关系数据库持久化 Hibernate参考文档 3.2 -------------------------------------------------------------------------------- 目录 前言 1. 翻译说明 2. 版权声明 1. Hibernate...

    用Hibernate3.1实现XML和数据库的同步

    6. **SchemaExport工具**:`org.hibernate.tool.hbm2ddl.SchemaExport`工具可用于根据`.hbm.xml`文件自动生成数据库表结构,简化了数据库初始化和维护工作。 #### 实践步骤详解 - **环境搭建**:首先,需确保已...

    Hibernate3中文帮助手册

    手册还会涵盖一些高级特性,如CGLIB和JPA支持、延迟加载(Lazy Loading)、级联操作(Cascading)、事件监听器、性能调优以及Hibernate工具(如SchemaExport工具,用于生成数据库表结构)等。 七、最佳实践与案例...

    hibernate入门

    Hibernate提供了诸如SchemaExport、SchemaUpdate等工具,用于根据实体类自动生成数据库表结构,或者同步数据库结构,简化了数据库的维护工作。 10. **最佳实践** 使用Hibernate时,应注意不要滥用Session,避免...

    hibernate3.5.0_final 所有参考文档 reference pdf

    4. **工具和API**:介绍了Hibernate提供的各种工具,如SchemaExport用于生成数据库表结构,以及各种API的使用方法。 5. **扩展与插件**:讲解了如何扩展Hibernate,如自定义拦截器、事件监听器等,以及第三方插件的...

    Hibernate工作中应用的总结.doc

    在IT行业中,Hibernate是一个广泛使用的对象关系映射(ORM)框架,它简化了Java应用程序与数据库之间的交互。以下是对Hibernate在实际工作应用中的总结,旨在帮助开发者更好地理解和使用Hibernate。 1. **项目配置*...

Global site tag (gtag.js) - Google Analytics