-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Create EntityManagerFactory programmatically?
PostPosted: Fri May 03, 2013 12:02 pm 
Regular
Regular

Joined: Tue Mar 22, 2005 2:27 am
Posts: 62
Hi All,

We found the following example of how to create an EntityManagerFactory which seems to work well:

Code:
        Properties properties = new Properties();
        properties.put("javax.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
        properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
        properties.put("hibernate.connection.username", "sa");
        properties.put("hibernate.connection.password", "");
        properties.put("hibernate.connection.driver_class", "org.h2.Driver");
        properties.put("hibernate.connection.url", "jdbc:h2:.");
        properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");

        Ejb3Configuration cfg = new Ejb3Configuration();
        cfg.addProperties(properties);
        cfg.addAnnotatedClass(ReportBuild.class);

        EntityManagerFactory factory = cfg.buildEntityManagerFactory();


The problem is that Ejb3Configuration now appears to be deprecated and slated for removal.
Is there a way to accomplish the same thing using non-deprecated APIs?
Specifically, we want no hibernate.hbm.xml or persistence.xml defined and also want to avoid classpath scanning, hence the explicit calls to cfg.addAnnotatedClass().

I tried the following, but it does classpath scanning and also requires a nearly empty persistence.xml just so that the persistent-unit name can be found (otherwise it errors out):

Code:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="MyPersistenceUnit"/>
</persistence>


Code:
        Properties properties = new Properties();
        properties.put("javax.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
        properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
        properties.put("hibernate.connection.username", "sa");
        properties.put("hibernate.connection.password", "");
        properties.put("hibernate.connection.driver_class", "org.h2.Driver");
        properties.put("hibernate.connection.url", "jdbc:h2:.");
        properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
       
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyPersistenceUnit", properties);
        return factory.createEntityManager();


Thanks,

Frank Grimes


Top
 Profile  
 
 Post subject: Re: Create EntityManagerFactory programmatically?
PostPosted: Tue May 07, 2013 9:39 am 
Newbie

Joined: Wed Feb 29, 2012 5:55 am
Posts: 6
Hi Frank,

we had to instantiate our EntitiyManagerFytory programatically, too, because we hab to set some additional Properties, we couldn't set by persistence.xml (i.e. instances for MultiTenantConnectionProvider and CurrentTenantConnectionProvider). So some of the stuff in this listing will be unneccessary for your case.

We're using classpath scanning, but I guess, you can skip this, if you add
Code:
pui.addManagedClassName(MyEntity.class.getName());

to the PersistenceUnitPostProcessor#postProcessPersistenceUnitInfo(...).

Code:
public EntityManagerFactory entityManagerFactory(final CurrentTenantIdentifierResolver currentTenantIdentifierResolver,
                                                     final MultiTenantConnectionProvider multiTenantConnectionProvider,
                                                     DataSource dataSource)
        throws PropertyVetoException {
        LocalContainerEntityManagerFactoryBean emff = new LocalContainerEntityManagerFactoryBean();
        emff.setPersistenceUnitName(this.persistenceUnit);
        emff.setPackagesToScan(entityPackages);
        emff.setDataSource(dataSource);
        emff.setJpaVendorAdapter(jpaVendorAdapter());
        Properties jpaProperties = new Properties();
        jpaProperties.setProperty(org.hibernate.ejb.AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE.name());
        emff.setJpaProperties(jpaProperties);
        emff.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() {

            @Override
            public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
                if (!pui.getPersistenceUnitName().equals(persistenceUnit)){
                    return;
                }
                Properties props = pui.getProperties();
                props.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
                props.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
                props.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
                if (useEntityCache){
                    props.put(AvailableSettings.USE_SECOND_LEVEL_CACHE,true);
                    props.put(AvailableSettings.CACHE_REGION_FACTORY, "org.hibernate.cache.ehcache.EhCacheRegionFactory");
                    if (!ehcacheConfigFile.exists()){
                        throw new FatalBeanException("EHCache config file doesn't exist");
                    }
                    try {
                        props.put("net.sf.ehcache.configurationResourceName",ehcacheConfigFile.getURL().toExternalForm());
                    }
                    catch (IOException e) {
                        //Should never happen
                        throw new AssertionError(e);
                    }
                }
                else{
                    props.put(AvailableSettings.USE_SECOND_LEVEL_CACHE,false);
                }
                props.put(AvailableSettings.GENERATE_STATISTICS, true);
            }
        });

        emff.afterPropertiesSet();

        return emff.getObject();
    }


Top
 Profile  
 
 Post subject: Re: Create EntityManagerFactory programmatically?
PostPosted: Tue May 07, 2013 12:15 pm 
Regular
Regular

Joined: Tue Mar 22, 2005 2:27 am
Posts: 62
Are you sure your code doesn't require a persistence.xml file?

"Internally, this FactoryBean parses the persistence.xml file itself and creates a corresponding PersistenceUnitInfo object"

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.