JPA:从属性创建EntityManagerFactory [英] JPA: create EntityManagerFactory from properties

查看:123
本文介绍了JPA:从属性创建EntityManagerFactory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JAR-Project中使用JPA并使用persistence.xml来设置我的EntityManager。

i am using JPA in a JAR-Project and used the persistence.xml to setup my EntityManager.

但是由于persistence.xml在构建之后位于JAR内部,因此用户之后更改设置非常复杂。所以我正在寻找一个解决方案,我可以通过在运行时加载的属性文件配置我的连接。

But since the persistence.xml is inside the JAR after the build it is very complicated for the user to change the settings afterwards. So i'm looking for a solution where i can configure my connection over a propertyfile which is loaded at runtime.

我在网上遇到了这个解决方案:

I came across this solution on the 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);

这是我正在寻找的解决方案,但我在这里缺少一件事:在我的坚持中。 xml我还在映射文件上声明了一个模式名称:

Which is the solution i was looking for but i'm missing one thing here: In my persistence.xml i also declare a schema name over a mapping file:

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>

所以我的问题基本上是:我是否可以使用在运行时设置架构的属性,就像我对其他房产一样吗?

So my question is basically: Is there a property i can use to set the schema at runtime, just like i do with the other properties?

或者是否有更好的解决方案?

Or is there even a better solution?

提前致谢!

推荐答案

切换到java配置。然后,您可以通过自动装配环境轻松注入属性值

Switch to java config. Then you can easily inject property values by autowiring Environment

此示例非常基本。但总的来说,如果您知道如何进行xml配置,则可以将其直接映射到Java配置

This example is extremely basic. But in general if you know how to do the xml config you can map it straight onto the Java config

contextConfig.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

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;
    }

}

这篇关于JPA:从属性创建EntityManagerFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆