hibernate - Spring 3/Hibernate - 在运行时执行数据库转储

标签 hibernate spring mysql spring-roo database-dump

我正在使用 spring roo 开发一个应用程序,它使用 spring 3 和 hibernate。
由于后端的构建不是一个高效的后端,因此我可以选择将数据设置回转储。

如果用户提交 jsp 表单,则应“执行”此转储。 我可以加载 Dump.sql 文件,一切都很好,只是我不知道如何执行它。 我尝试了几种方法:
1. 使用实体管理器进行 native 查询:

Query q = entityManager.createNativeQuery(dump);  
q.executeUpdate();

但它不起作用(hibernate异常)我认为这是因为hibernate无法“读取”mysql导出的Dump.sql文件”
2. 方法是只使用 hibernate:

Configuration cfg = new Configuration();  
File configFile = new     File(getClass().getClassLoader().getResource("/METAINF/persistence.xml").toURI());  
cfg.configure(configFile);  
SessionFactory sf=cfg.buildSessionFactory();  
Session sess=sf.openSession();  
Statement st;  
st = sess.connection().createStatement();  

但它也不起作用:

org.hibernate.MappingException:无效配置 导致:org.xml.sax.SAXParseException:文档无效:找不到语法。

有什么建议吗?

最佳答案

我曾经编写过一个Java类,它从数据库转储数据,然后将其导入到另一个数据库(但它不使用MySQL生成的转储)。也许你会看一下。

该类依赖于DdlUtilsDbUnit :

import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.model.Database;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Dumper between databases.
 * 
 * @author ndeverge
 */
public final class DatabaseDumper {

    /**
     * Le logger.
     */
    private static final Log LOGGER = LogFactory.getLog(DatabaseDumper.class);

    /**
     * Environment (dev, continuous integration etc...).
     */
    @Value("#{envProperties['env']}")
    private String env;

    /**
     * The db to dump data from.
     */
    @Autowired
    @Qualifier("referenceDataSource")
    private DataSource sourceDataSource;

    /**
     * the db where to write data to.
     */
    @Autowired
    @Qualifier("dataSource")
    private DataSource destDataSource;

    /**
     * Do we need to run the dump ?
     */
    private boolean doRun;

    /**
     * @return the doRun
     */
    public boolean isDoRun() {
        if (doRun) {
            return true;
        }
        // run the dump only on continuous-integration environment
        if ("continuous-integration".equalsIgnoreCase(env)) {
            return true;
        }
        return false;
    }

    /**
     * @param aDoRun
     *            the doRun to set
     */
    public void setDoRun(final boolean aDoRun) {
        doRun = aDoRun;
    }

    /**
     * Set datasources if not initialized by Spring.<br>
     * This method is used when this utility is started from command line.
     * 
     * @throws SQLException
     *             on errors
     */
    private void initDataSources() throws SQLException {

        if (sourceDataSource == null || destDataSource == null) {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring/dbDumperContext.xml");

            sourceDataSource = (DataSource) context.getBean("referenceDataSource");

            destDataSource = (DataSource) context.getBean("dataSource");
        }

    }

    /**
     * Dumper execution.
     * 
     * @throws Exception
     *             on errors
     */
    public void execute() throws Exception {

        if (!isDoRun()) {
            LOGGER.debug("Do not run the dump for environment \"" + env + "\"");
        } else {

            LOGGER.warn("WARNING !!! Running the database dump, it may take some time...");

            long start = System.currentTimeMillis();

            // extract schema
            Database schema = dumpSchema(sourceDataSource);

            // create schema
            createSchema(destDataSource, schema);

            // extract data
            IDataSet dataSet = dumpData(sourceDataSource);

            // import data
            importData(destDataSource, dataSet);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Database dump duration = " + (System.currentTimeMillis() - start) + " ms");
            }
        }
    }

    /**
     * Extract schema using ddlutils.
     * 
     * @param aSourceDataSource
     *            source db
     * @return an outputstream containing the schema
     * @throws DatabaseUnitException
     *             on errors
     * @throws SQLException
     *             on errors
     * @throws IOException
     *             on errors
     */
    private IDataSet dumpData(final DataSource aSourceDataSource) throws DatabaseUnitException, SQLException,
            IOException {
        IDatabaseConnection sourceConnection = new DatabaseConnection(aSourceDataSource.getConnection());

        return sourceConnection.createDataSet();
    }

    /**
     * Extract data using dbUnit.
     * 
     * @param aSourceDataSource
     *            source db
     * @return an outputstream containing the data
     */
    private Database dumpSchema(final DataSource aSourceDataSource) {
        return PlatformFactory.createNewPlatformInstance(aSourceDataSource).readModelFromDatabase("sourceModel");

    }

    /**
     * Create schema in destination db.
     * 
     * @param aDestDataSource
     *            the destination db
     * @param schema
     *            the schema
     */
    private void createSchema(final DataSource aDestDataSource, final Database schema) {
        Platform destPlatform = PlatformFactory.createNewPlatformInstance(aDestDataSource);

        // create schema by droping tables firts (2nd parameter = true)
        destPlatform.createTables(schema, true, true);
    }

    /**
     * Data import.
     * 
     * @param aDestDataSource
     *            the destination db
     * @param dataSet
     *            the data
     * @throws SQLException
     *             on errors
     * @throws DatabaseUnitException
     *             on errors
     */
    private void importData(final DataSource aDestDataSource, final IDataSet dataSet) throws DatabaseUnitException,
            SQLException {
        IDatabaseConnection destConnection = new DatabaseConnection(aDestDataSource.getConnection());

        DatabaseOperation.CLEAN_INSERT.execute(destConnection, dataSet);
    }

    /**
     * Launch the dumper from commande line.
     * 
     * @param args
     *            paramètres
     */
    public static void main(final String[] args) {
        try {
            DatabaseDumper dumper = new DatabaseDumper();
            dumper.setDoRun(true);
            dumper.initDataSources();
            dumper.execute();
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

}

关于hibernate - Spring 3/Hibernate - 在运行时执行数据库转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9307686/

相关文章:

java - 为什么 Tomcat 会为我的应用程序打开那么多 Java 进程?

java - Spring应用程序上下文在ApplicationContextAware类中为空

php - 在 PHP 循环中插入多个 SQL 查询

php - 保护 MySQL 密码和管理多个帐户的最佳做法是什么?

java - 缺少具有 EmbeddedId 的实体的默认构造函数

Java、PostgreSQL 和 Hibernate : Select statement with nested strings

performance - 如何提高向数据库插入数据的性能?

java - POM 中的 NoClassDefFoundError : javax/validation/Validation occurs even validation-api 1. 1.0.Final

java - 在代码中使用 Spring 的 TransactionAwareDataSourceProxy,而不是 xml

MySQL LOAD 数据性能