3

JAR プロジェクトで JPA を使用しており、persistence.xml を使用して EntityManager をセットアップしました。

しかし、persistence.xml はビルド後に JAR 内にあるため、後でユーザーが設定を変更するのは非常に複雑です。だから私は、実行時にロードされるプロパティファイルを介して接続を構成できるソリューションを探しています。

Webでこのソリューションに出会いました:

Map properties = new HashMap();

// Configure the internal EclipseLink connection pool
properties.put(JDBC_DRIVER, "oracle.jdbc.OracleDriver");
properties.put(JDBC_URL, "jdbc:oracle:thin:@localhost:1521:ORCL");
properties.put(JDBC_USER, "user-name");
properties.put(JDBC_PASSWORD, "password");

Persistence.createEntityManagerFactory("unit-name", properties);

これは私が探していたソリューションですが、ここで1つ欠けています:私のpersistence.xmlでは、マッピングファイルでスキーマ名も宣言しています:

persistence.xml:

<persistence version="2.0" ...>
  <persistence-unit name="jpa" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>...</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="..."/>
      <property name="javax.persistence.jdbc.password" value="..."/>
      <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
      <property name="javax.persistence.jdbc.user" value="..."/>
    </properties>
    <mapping-file>META-INF/orm.xml</mapping-file>
  </persistence-unit>
</persistence>

orm.xml:

<entity-mappings ...>
 <persistence-unit-metadata>
  <persistence-unit-defaults>
   <schema>SCHEMA_NAME</schema>
  </persistence-unit-defaults>
 </persistence-unit-metadata>
</entity-mappings>

したがって、私の質問は基本的に次のとおりです。他のプロパティと同じように、実行時にスキーマを設定するために使用できるプロパティはありますか?

それとももっと良い解決策がありますか?

前もって感謝します!

4

4 に答える 4

2

Java 構成に切り替えます。次に、環境を自動配線することでプロパティ値を簡単に注入できます

この例は非常に基本的なものです。ただし、一般に、xml 構成の実行方法を知っていれば、それを直接 Java 構成にマップできます。

contextConfig.java

/**
 * Spring Context configuration.
 */
@ComponentScan(basePackages = { "com.example" })
@PropertySource({ "classpath:common.properties" })
@Configuration
@Import(JpaConfig.class)
public class ContextConfig extends WebMvcConfigurerAdapter {
    /**
     * This bean is needed because Spring when you use xml config to load property files the bean is automatically
     * created... when you use @PropertySource then not so much
     * @return new bean
     */
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

jpaConfig.java

@Configuration
@EnableJpaRepositories("com.example.repository")
public class JpaConfig {

    @Autowired
    private Environment env;

    /**
     * Create the fooDataSource Bean.
     * @return fooDataSource Bean
     */
    @Bean
    public BasicDataSource fooDataSource() {

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(env.getProperty("cfg_foo.driver.name"));
        basicDataSource.setUrl(env.getProperty("cfg_foo.jdbc.url"));
        basicDataSource.setUsername(env.getProperty("cfg_foo.username"));
        basicDataSource.setPassword(env.getProperty("cfg_foo.password"));
        basicDataSource.setPoolPreparedStatements(Boolean.valueOf(env.getProperty("cfg_foo.poolPreparedStatements")));
        basicDataSource.setInitialSize(Integer.valueOf(env.getProperty("cfg_foo.poolInitialSize")));
        basicDataSource.setMaxActive(Integer.valueOf(env.getProperty("cfg_foo.poolMaxActive")));
        basicDataSource.setMaxIdle(Integer.valueOf(env.getProperty("cfg_foo.poolMaxIdle")));
        basicDataSource.setValidationQuery("SELECT '1'");

        return basicDataSource;
    }

    /**
     * Create the hibernateJpaVendorAdapter Bean.
     * @return hibernateJpaVendorAdapter Bean
     */
    @Bean
    public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {

        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
        adapter.setShowSql(Boolean.valueOf(env.getProperty("show.sql")));
        adapter.setGenerateDdl(Boolean.valueOf(env.getProperty("format.sql")));

        return adapter;
    }

    /**
     * Create the entityManagerFactory Bean.
     * @return entityManagerFactory Bean
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setPersistenceUnitName("foo");
        entityManagerFactory.setDataSource(fooDataSource());
        entityManagerFactory.setJpaVendorAdapter(hibernateJpaVendorAdapter());
        entityManagerFactory.setPackagesToScan("com.example.repository");

        return entityManagerFactory;
    }

}
于 2013-08-01T08:44:37.977 に答える
0

META-INF/orm.xmlはデフォルト名で、ファイルが存在する場合は、永続化ユニットで指定されているかどうかに関係なく使用されます。のマッピング ファイルにpersistence.xml別の名前がある場合、デフォルト名は使用されません。

SQL Server や Oracle など、互換性のないいくつかのデータベース プロバイダを使用するために、 に複数の持続性ユニットを用意し、persistence.xml実行時に適切なユニットを選択することができます。マッピング ファイルにデフォルト以外の名前が付けられている場合、各ユニットは独自のマッピング ファイルを持つことも、何も持たないこともあります。

于 2016-04-02T19:57:19.957 に答える