在init之前的Hibernate config.Run sql脚本

时间:2017-12-05 21:51:33

标签: java hibernate

我在我的项目中使用H2-in-memory数据库,我想在启动之前运行几个sql脚本。 这是我的配置:

  

hibernate.dialect = org.hibernate.dialect.H2Dialect   hibernate.show_sql =真   hibernate.hbm2ddl.auto =无   hibernate.hbm2ddl.import_files =" /db/scripts/schema.sql,/db/scripts/insert-users.sql

但它不起作用。如果我将hibernate.hbm2ddl.auto更改为createcreate-drop,则会尝试根据带注释的实体创建表。但是我希望通过创建表和插入用户来运行我自己的sql脚本。 Java配置:

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(restDataSource());
    sessionFactory.setPackagesToScan(
            new String[]{"org.training.ytaranau"});
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
}
 Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.hbm2ddl.auto",
                    env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect",
                    env.getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers",
                    "true");
            setProperty("hibernate.hbm2ddl.import_files",
                    env.getProperty("hibernate.hbm2ddl.import_files"));
        }
    };
}

我能做到吗?

1 个答案:

答案 0 :(得分:-1)

您可以在下面为休眠设置属性,然后可以执行一些脚本。

javax.persistence.schema-generation.create-source
javax.persistence.sql-load-script-source

     <property name="javax.persistence.schema-generation.drop-script-source" value="META-INF/drop-script.sql"/>
     <property name="javax.persistence.schema-generation.create-script-source" value="META-INF/create-script.sql"/>