86

有没有办法在EntityManager没有定义持久性单元的情况下初始化?您能否提供创建实体管理器所需的所有属性?我需要EntityManager在运行时从用户指定的值创建。更新persistence.xml和重新编译不是一种选择。

任何关于如何做到这一点的想法都非常受欢迎!

4

7 回答 7

59

有没有办法在EntityManager没有定义持久性单元的情况下初始化?

您应该在部署描述符中至少定义一个持久性单元。persistence.xml

你能给出创建一个所需的所有属性Entitymanager吗?

  • name 属性是必需的。其他属性和元素是可选的。(JPA 规范)。所以这应该或多或少是你的最小persistence.xml文件:
<persistence>
    <persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
        SOME_PROPERTIES
    </persistence-unit>
</persistence>

在 Java EE 环境中,jta-data-sourcenon-jta-data-source元素用于指定持久性提供程序要使用的 JTA 和/或非 JTA 数据源的全局 JNDI 名称。

因此,如果您的目标应用程序服务器支持 JTA(JBoss、Websphere、GlassFish),您的persistence.xml外观如下:

<persistence>
    <persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
        <!--GLOBAL_JNDI_GOES_HERE-->
        <jta-data-source>jdbc/myDS</jta-data-source>
    </persistence-unit>
</persistence>

如果您的目标应用程序服务器不支持 JTA (Tomcat),您的persistence.xml外观如下:

<persistence>
    <persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
        <!--GLOBAL_JNDI_GOES_HERE-->
        <non-jta-data-source>jdbc/myDS</non-jta-data-source>
    </persistence-unit>
</persistence>

如果您的数据源未绑定到全局 JNDI(例如,在 Java EE 容器之外),那么您通常会定义 JPA 提供程序、驱动程序、url、用户和密码属性。属性名称取决于 JPA 提供者。因此,对于作为 JPA 提供者的 Hibernate,您的persistence.xml文件将如下所示:

<persistence>
    <persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>br.com.persistence.SomeClass</class>
        <properties>
            <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
            <property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/EmpServDB;create=true"/>
            <property name="hibernate.connection.username" value="APP"/>
            <property name="hibernate.connection.password" value="APP"/>
        </properties>
    </persistence-unit>
</persistence>

交易类型属性

通常,在 Java EE 环境中,事务类型RESOURCE_LOCAL假定将提供非 JTA 数据源。在 Java EE 环境中,如果未指定此元素,则默认为 JTA。在 Java SE 环境中,如果未指定此元素,RESOURCE_LOCAL则可以假定默认值为 。

  • 为了确保 Java SE 应用程序的可移植性,有必要明确列出包含在持久性单元中的托管持久性类(JPA 规范)

我需要EntityManager在运行时从用户指定的值创建

所以使用这个:

Map addedOrOverridenProperties = new HashMap();

// Let's suppose we are using Hibernate as JPA provider
addedOrOverridenProperties.put("hibernate.show_sql", true);

Persistence.createEntityManagerFactory(<PERSISTENCE_UNIT_NAME_GOES_HERE>, addedOrOverridenProperties);
于 2010-01-02T07:51:48.593 回答
29

是的,您可以在 @Configuration 类(或其等效的spring config xml)中使用这样的spring而不使用任何xml文件:

@Bean
public LocalContainerEntityManagerFactoryBean emf(){
    properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
    properties.put("javax.persistence.jdbc.url", dbConnectionURL);
    properties.put("javax.persistence.jdbc.user", dbUser); //if needed

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
    emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
    emf.setPersistenceUnitName(SysConstants.SysConfigPU);
    emf.setJpaPropertyMap(properties);
    emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
    return emf;
}
于 2012-08-26T01:15:03.970 回答
22

这是一个没有 Spring 的解决方案。常数取自org.hibernate.cfg.AvailableSettings

entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
            archiverPersistenceUnitInfo(),
            ImmutableMap.<String, Object>builder()
                    .put(JPA_JDBC_DRIVER, JDBC_DRIVER)
                    .put(JPA_JDBC_URL, JDBC_URL)
                    .put(DIALECT, Oracle12cDialect.class)
                    .put(HBM2DDL_AUTO, CREATE)
                    .put(SHOW_SQL, false)
                    .put(QUERY_STARTUP_CHECKING, false)
                    .put(GENERATE_STATISTICS, false)
                    .put(USE_REFLECTION_OPTIMIZER, false)
                    .put(USE_SECOND_LEVEL_CACHE, false)
                    .put(USE_QUERY_CACHE, false)
                    .put(USE_STRUCTURED_CACHE, false)
                    .put(STATEMENT_BATCH_SIZE, 20)
                    .build());

entityManager = entityManagerFactory.createEntityManager();

还有臭名昭著的PersistenceUnitInfo

private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
    return new PersistenceUnitInfo() {
        @Override
        public String getPersistenceUnitName() {
            return "ApplicationPersistenceUnit";
        }

        @Override
        public String getPersistenceProviderClassName() {
            return "org.hibernate.jpa.HibernatePersistenceProvider";
        }

        @Override
        public PersistenceUnitTransactionType getTransactionType() {
            return PersistenceUnitTransactionType.RESOURCE_LOCAL;
        }

        @Override
        public DataSource getJtaDataSource() {
            return null;
        }

        @Override
        public DataSource getNonJtaDataSource() {
            return null;
        }

        @Override
        public List<String> getMappingFileNames() {
            return Collections.emptyList();
        }

        @Override
        public List<URL> getJarFileUrls() {
            try {
                return Collections.list(this.getClass()
                                            .getClassLoader()
                                            .getResources(""));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        @Override
        public URL getPersistenceUnitRootUrl() {
            return null;
        }

        @Override
        public List<String> getManagedClassNames() {
            return Collections.emptyList();
        }

        @Override
        public boolean excludeUnlistedClasses() {
            return false;
        }

        @Override
        public SharedCacheMode getSharedCacheMode() {
            return null;
        }

        @Override
        public ValidationMode getValidationMode() {
            return null;
        }

        @Override
        public Properties getProperties() {
            return new Properties();
        }

        @Override
        public String getPersistenceXMLSchemaVersion() {
            return null;
        }

        @Override
        public ClassLoader getClassLoader() {
            return null;
        }

        @Override
        public void addTransformer(ClassTransformer transformer) {

        }

        @Override
        public ClassLoader getNewTempClassLoader() {
            return null;
        }
    };
}
于 2017-02-21T16:22:07.600 回答
19

我能够EntityManager纯粹使用 Java 代码(使用 Spring 配置)创建一个带有 Hibernate 和 PostgreSQL 的以下内容:

@Bean
public DataSource dataSource() {
    final PGSimpleDataSource dataSource = new PGSimpleDataSource();

    dataSource.setDatabaseName( "mytestdb" );
    dataSource.setUser( "myuser" );
    dataSource.setPassword("mypass");

    return dataSource;
}

@Bean
public Properties hibernateProperties(){
    final Properties properties = new Properties();

    properties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
    properties.put( "hibernate.connection.driver_class", "org.postgresql.Driver" );
    properties.put( "hibernate.hbm2ddl.auto", "create-drop" );

    return properties;
}

@Bean
public EntityManagerFactory entityManagerFactory( DataSource dataSource, Properties hibernateProperties ){
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource( dataSource );
    em.setPackagesToScan( "net.initech.domain" );
    em.setJpaVendorAdapter( new HibernateJpaVendorAdapter() );
    em.setJpaProperties( hibernateProperties );
    em.setPersistenceUnitName( "mytestdomain" );
    em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    em.afterPropertiesSet();

    return em.getObject();
}

调用 toLocalContainerEntityManagerFactoryBean.afterPropertiesSet()必不可少的,否则工厂永远不会被构建,然后getObject()返回并且你整天null都在追逐s 。NullPointerException>:-(

然后它使用以下代码:

PageEntry pe = new PageEntry();
pe.setLinkName( "Google" );
pe.setLinkDestination( new URL( "http://www.google.com" ) );

EntityTransaction entTrans = entityManager.getTransaction();
entTrans.begin();
entityManager.persist( pe );
entTrans.commit();

我的实体在哪里:

@Entity
@Table(name = "page_entries")
public class PageEntry {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String linkName;
    private URL linkDestination;

    // gets & setters omitted
}
于 2014-11-08T06:51:14.480 回答
8

使用普通 JPA,假设您有一个PersistenceProvider实现(例如 Hibernate),您可以使用PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map)方法来引导一个,EntityManagerFactory而无需persistence.xml.

但是,您必须实现PersistenceUnitInfo接口很烦人,因此最好使用 Spring 或 Hibernate,它们都支持在没有persistence.xml文件的情况下引导 JPA:

this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
    this.persistenceUnitInfo, 
    getJpaPropertyMap()
);

其中PersistenceUnitInfo由 Spring 特定的MutablePersistenceUnitInfo类实现。

于 2016-09-20T13:18:26.090 回答
0

我使用的 DataNucleus JPA在其文档中也有这样做的方法。不需要 Spring 或丑陋的PersistenceUnitInfo.

只需执行以下操作

import org.datanucleus.metadata.PersistenceUnitMetaData;
import org.datanucleus.api.jpa.JPAEntityManagerFactory;

PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("mydomain.test.A");
pumd.setExcludeUnlistedClasses();
pumd.addProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:nucleus");
pumd.addProperty("javax.persistence.jdbc.user", "sa");
pumd.addProperty("javax.persistence.jdbc.password", "");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");

EntityManagerFactory emf = new JPAEntityManagerFactory(pumd, null);
于 2018-11-27T09:24:46.323 回答
0

您还可以使用 PersistenceContext 或 Autowired 注释获取 EntityManager,但请注意它不是线程安全的。

@PersistenceContext
private EntityManager entityManager;
于 2020-08-13T05:48:21.403 回答