使用基于Java的配置在服务器模式下设置H2

使用基于Java的配置在服务器模式下设置H2,java,spring,hibernate,configuration,h2,Java,Spring,Hibernate,Configuration,H2,我有spring XML,它使我能够使用以下配置在服务器模式下启动H2数据库: <beans profile="test-h2"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.h2.Driver

我有spring XML,它使我能够使用以下配置在服务器模式下启动H2数据库:

<beans profile="test-h2">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:target/h2/pps;AUTO_SERVER=TRUE"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
    <bean id="entityManagerFactory" parent="entityManagerFactoryCommonParent">
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
private static final String H2_JDBC_URL_TEMPLATE = "jdbc:h2:%s/target/db/sample;AUTO_SERVER=TRUE";
@Value("classpath:seed-data.sql")
private Resource H2_SCHEMA_SCRIPT;

@Value("classpath:test-data.sql")
private Resource H2_DATA_SCRIPT;

@Value("classpath:drop-data.sql")
private Resource H2_CLEANER_SCRIPT;


@Bean
public DataSource dataSource(Environment env) throws Exception {
        return createH2DataSource();
}


@Autowired
@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {

    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    initializer.setDatabaseCleaner(databaseCleaner());
    return initializer;
}


private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(H2_SCHEMA_SCRIPT);
    populator.addScript(H2_DATA_SCRIPT);
    return populator;
}

private DatabasePopulator databaseCleaner() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(H2_CLEANER_SCRIPT);
    return populator;
}

private DataSource createH2DataSource() {
    String jdbcUrl = String.format(H2_JDBC_URL_TEMPLATE, System.getProperty("user.dir"));
    JdbcDataSource ds = new JdbcDataSource();       
    ds.setURL(jdbcUrl);
    ds.setUser("sa");
    ds.setPassword("");

    return ds;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(Environment env) throws Exception {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);     

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setPersistenceUnitName("sample");
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.sample.model");
    factory.setDataSource(dataSource(env));     

    factory.setJpaProperties(jpaProperties());
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());

    return factory;
}

Properties jpaProperties() {
    Properties props = new Properties();
    props.put("hibernate.query.substitutions", "true 'Y', false 'N'");
    props.put("hibernate.hbm2ddl.auto", "create-drop");
    props.put("hibernate.show_sql", "false");
    props.put("hibernate.format_sql", "true");

    return props;
}

也许使用EmbeddedDatabaseBuilder(ResourceLoader)可以工作。有人提供了一些示例代码吗?

我认为这是不可能的。术语Embedded database是指不需要服务器的数据库,并且嵌入到应用程序中,因此不应为此使用EmbeddedDatabase

在h2文档中,“嵌入式”一词被赋予了“本地”(连接到嵌入式(本地)数据库),当他们使用“服务器”时,他们谈论的是由服务器管理数据库的远程连接。为了加强这一想法,EmbeddedDataSource接口只添加了一个在datasource“shutdown”接口中不存在的方法,该接口通常用于在应用程序关闭时通过
@Bean(destromethod=“shutdown”)
关闭数据库

请参阅此处的更多详细信息:


以下代码允许您使用基于java的spring配置在服务器模式下启动H2数据库:

<beans profile="test-h2">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:target/h2/pps;AUTO_SERVER=TRUE"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
    <bean id="entityManagerFactory" parent="entityManagerFactoryCommonParent">
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
private static final String H2_JDBC_URL_TEMPLATE = "jdbc:h2:%s/target/db/sample;AUTO_SERVER=TRUE";
@Value("classpath:seed-data.sql")
private Resource H2_SCHEMA_SCRIPT;

@Value("classpath:test-data.sql")
private Resource H2_DATA_SCRIPT;

@Value("classpath:drop-data.sql")
private Resource H2_CLEANER_SCRIPT;


@Bean
public DataSource dataSource(Environment env) throws Exception {
        return createH2DataSource();
}


@Autowired
@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {

    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    initializer.setDatabasePopulator(databasePopulator());
    initializer.setDatabaseCleaner(databaseCleaner());
    return initializer;
}


private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(H2_SCHEMA_SCRIPT);
    populator.addScript(H2_DATA_SCRIPT);
    return populator;
}

private DatabasePopulator databaseCleaner() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(H2_CLEANER_SCRIPT);
    return populator;
}

private DataSource createH2DataSource() {
    String jdbcUrl = String.format(H2_JDBC_URL_TEMPLATE, System.getProperty("user.dir"));
    JdbcDataSource ds = new JdbcDataSource();       
    ds.setURL(jdbcUrl);
    ds.setUser("sa");
    ds.setPassword("");

    return ds;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(Environment env) throws Exception {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);     

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setPersistenceUnitName("sample");
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.sample.model");
    factory.setDataSource(dataSource(env));     

    factory.setJpaProperties(jpaProperties());
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());

    return factory;
}

Properties jpaProperties() {
    Properties props = new Properties();
    props.put("hibernate.query.substitutions", "true 'Y', false 'N'");
    props.put("hibernate.hbm2ddl.auto", "create-drop");
    props.put("hibernate.show_sql", "false");
    props.put("hibernate.format_sql", "true");

    return props;
}

到目前为止,这完全是矫枉过正。同样的事情也可以在几行中完成。我与作者没有任何关系,但他的指示确实对我起了作用。