Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit using the given properties.

Usage

From source file:org.eclipse.om2m.persistence.eclipselink.internal.DBServiceJPAImpl.java

public void init() {
    LOGGER.info("Initializing Database...");
    try {/*  w w  w . j av a  2 s.  c  o m*/
        Map<Object, Object> properties = new HashMap<Object, Object>();
        properties.put(PersistenceUnitProperties.JDBC_DRIVER, DBConstants.DB_DRIVER);
        properties.put(PersistenceUnitProperties.JDBC_URL, DBConstants.DB_URL);
        properties.put(PersistenceUnitProperties.JDBC_USER, DBConstants.DB_USER);
        properties.put(PersistenceUnitProperties.JDBC_PASSWORD, DBConstants.DB_PASSWORD);
        properties.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, DBConstants.DB_CACHE);

        if (DBConstants.DB_VERBOSE) {
            properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "FINE");
        } else {
            properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "SEVERE");
        }

        if (DBConstants.DB_RESET) {
            properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
        } else {
            properties.put(PersistenceUnitProperties.DDL_GENERATION,
                    PersistenceUnitProperties.CREATE_OR_EXTEND);
        }

        LOGGER.info("Creating new EntityManagerFactory...");
        emf = Persistence.createEntityManagerFactory("om2mdb", properties);
    } catch (Exception e) {
        LOGGER.error("Error in creation of EntityManagerFactory", e);
    }
    if (emf != null) {
        LOGGER.info("DataBase initialized.");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.close();
    } else {
        LOGGER.error("ERROR initializing Database: EntityManagerFactory is null!");
    }
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * DS activate method./*  ww w. j a  va 2  s  .c  o  m*/
 * 
 * @param context
 *          ComponentContext
 * 
 * @throws Exception
 *           if any error occurs
 */
protected void activate(final ComponentContext context) throws Exception {
    EntityManager em = null;
    try {
        readConfiguration();
        if (!_properties.containsKey("eclipselink.logging.file")) {
            final File workingDir = WorkspaceHelper.createWorkingDir(BUNDLE_NAME);
            final File logfile = new File(workingDir, "jpa.log");
            _properties.put("eclipselink.logging.file", logfile.getAbsolutePath());
        }
        // set up eclipseLink
        _emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, _properties);

        // create an initial EntityManager to create the database
        em = _emf.createEntityManager();
    } catch (final Exception e) {
        if (_log.isErrorEnabled()) {
            _log.error("error activating RecordStorageImpl service", e);
        }
        throw e;
    } finally {
        closeEntityManager(em);
    }
    if (_log.isTraceEnabled()) {
        _log.trace("started RecordStorageImpl service");
    }
}

From source file:org.seedstack.seed.persistence.jpa.internal.JpaPluginTest.java

public void mockPersitanceCreateEntityManagerFactory() {
    mockStatic(Persistence.class);
    when(Persistence.createEntityManagerFactory("hsql-in-memory", getProperties()))
            .thenReturn(mock(EntityManagerFactory.class));
}

From source file:org.apache.airavata.registry.core.app.catalog.util.AppCatalogJPAUtils.java

public static EntityManager getEntityManager() throws ApplicationSettingsException {
    if (factory == null) {
        String connectionProperties = "DriverClassName=" + readServerProperties(APPCATALOG_JDBC_DRIVER) + ","
                + "Url=" + readServerProperties(APPCATALOG_JDBC_URL) + "?autoReconnect=true," + "Username="
                + readServerProperties(APPCATALOG_JDBC_USER) + "," + "Password="
                + readServerProperties(APPCATALOG_JDBC_PWD) + ",validationQuery="
                + readServerProperties(APPCATALOG_VALIDATION_QUERY);
        System.out.println(connectionProperties);
        Map<String, String> properties = new HashMap<String, String>();
        properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource");
        properties.put("openjpa.ConnectionProperties", connectionProperties);
        properties.put("openjpa.DynamicEnhancementAgent", "true");
        properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported");
        // For app catalog, we don't need caching
        //            properties.put("openjpa.DataCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
        //            properties.put("openjpa.QueryCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
        properties.put("openjpa.RemoteCommitProvider", "sjvm");
        properties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO");
        properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
        properties.put("openjpa.jdbc.QuerySQLCache", "false");
        properties.put("openjpa.ConnectionFactoryProperties",
                "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    }//from w  w w  . j  a  v a  2  s. c o  m
    appCatEntityManager = factory.createEntityManager();
    return appCatEntityManager;
}

From source file:org.apache.roller.weblogger.planet.business.jpa.JPARollerPlanetPersistenceStrategy.java

/**
 * Uses database configuration information from WebloggerConfig (i.e. roller-custom.properties)
 * //from   w w  w. j a va2 s .  c o  m
 * @throws org.apache.roller.PlanetException on any error
 */
protected JPARollerPlanetPersistenceStrategy() throws PlanetException {

    DatabaseProvider dbProvider = WebloggerStartup.getDatabaseProvider();

    String jpaConfigurationType = PlanetConfig.getProperty("jpa.configurationType");
    if ("jndi".equals(jpaConfigurationType)) {
        // If JNDI configuration type specified in Planet Config then use it
        // Lookup EMF via JNDI: added for Geronimo
        String emfJndiName = "java:comp/env/" + PlanetConfig.getProperty("jpa.emf.jndi.name");
        try {
            emf = (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
        } catch (NamingException e) {
            throw new PlanetException("Could not look up EntityManagerFactory in jndi at " + emfJndiName, e);
        }

    } else {

        // Add all JPA, OpenJPA, HibernateJPA, etc. properties found
        Properties emfProps = new Properties();
        Enumeration keys = WebloggerConfig.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            if (key.startsWith("javax.persistence.") || key.startsWith("openjpa.")
                    || key.startsWith("hibernate.")) {
                String value = WebloggerConfig.getProperty(key);
                logger.info(key + ": " + value);
                emfProps.setProperty(key, value);
            }
        }

        if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {
            emfProps.setProperty("javax.persistence.nonJtaDataSource", dbProvider.getJndiName());

        } else {
            emfProps.setProperty("javax.persistence.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("javax.persistence.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("javax.persistence.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("javax.persistence.jdbc.password", dbProvider.getJdbcPassword());
        }

        try {
            emf = Persistence.createEntityManagerFactory("PlanetPU", emfProps);
        } catch (PersistenceException pe) {
            logger.error("ERROR: creating entity manager", pe);
            throw new PlanetException(pe);
        }
    }
}

From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java

@Test
@PerfTest(invocations = 10)// w w  w  .j  ava 2s.c  o  m
public void testCRUDWithBatch() {
    Map<String, String> batchProperty = new HashMap<String, String>(1);
    batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, "5");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    Assert.assertEquals(5, ((Batcher) client).getBatchSize());

    final String originalName = "vivek";

    for (int i = 0; i < 9; i++) {
        PersonCouchDB object = new PersonCouchDB();
        object.setAge(32);
        object.setPersonId(ROW_KEY + i);
        object.setPersonName(originalName);
        em.persist(object);

        if (i >= 5) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNull(result);
        } else if (i > 0 && i % 4 == 0) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNotNull(result);
            Assert.assertEquals(result.getPersonId(), object.getPersonId());
            Assert.assertEquals(result.getAge(), object.getAge());
            Assert.assertEquals(result.getPersonName(), object.getPersonName());
        }
    }
    em.flush();
    em.clear();
    em.close();
    em = null;
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Activate./* w  w  w. ja  v a2s  .  c o m*/
 * 
 * @param context
 *          the context
 * @throws Exception
 *           if any error occurs
 */
protected synchronized void activate(final ComponentContext context) throws Exception {
    EntityManager em = null;
    try {
        readConfiguration();
        if (!_properties.containsKey("eclipselink.logging.file")) {
            final File workingDir = WorkspaceHelper.createWorkingDir(BUNDLE_NAME);
            final File logfile = new File(workingDir, "jpa.log");
            _properties.put("eclipselink.logging.file", logfile.getAbsolutePath());
        }
        // set up eclipseLink
        _emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, _properties);

        // create an initial EntityManager to create the database
        em = _emf.createEntityManager();
    } catch (final Exception e) {
        if (_log.isErrorEnabled()) {
            _log.error("error activating " + getClass(), e);
        }
        throw e;
    } finally {
        closeEntityManager(em);
    }
    if (_log.isTraceEnabled()) {
        _log.trace("Activating " + getClass());
    }
}

From source file:org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.AttachmentMgtDAOConnectionFactoryImpl.java

@Override
public void init() {
    if (transactionManager == null) {
        log.debug("Transaction-Manager is not initialized before initializing entityManager. So internal "
                + "transaction-manager in entity manager will be used.");
    }/*from  w w w .j a  va  2  s .  c  om*/

    JPAVendorAdapter vendorAdapter = getJPAVendorAdapter();
    //Here we pass a "null" valued transaction manager,
    // as we enforce the entity-manager-factory to use its local transactions. In future,
    // if required to use external JTA transactions, a transaction reference should be passed
    // as the input parameter.
    this.entityManagerFactory = Persistence.createEntityManagerFactory("Attachment-Mgt-PU",
            vendorAdapter.getJpaPropertyMap(null));
}

From source file:org.apache.airavata.sharing.registry.db.utils.JPAUtils.java

public synchronized static EntityManager getEntityManager() throws SharingRegistryException {
    if (factory == null) {
        String connectionProperties = "DriverClassName=" + readServerProperties(SHARING_REG_JDBC_DRIVER) + ","
                + "Url=" + readServerProperties(SHARING_REG_JDBC_URL) + "?autoReconnect=true," + "Username="
                + readServerProperties(SHARING_REG_JDBC_USER) + "," + "Password="
                + readServerProperties(SHARING_REG_JDBC_PWD) + ",validationQuery="
                + readServerProperties(SHARING_REG_VALIDATION_QUERY);

        //            String connectionProperties = "DriverClassName=com.mysql.jdbc.Driver," +
        //                    "Url=jdbc:mysql://localhost:3306/airavata_sharing_catalog?autoReconnect=true," +
        //                    "Username=root," +
        //                    "Password=," +
        //                    ",validationQuery=SELECT 1 FROM CONFIGURATION";

        Map<String, String> properties = new HashMap<String, String>();
        properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource");
        properties.put("openjpa.ConnectionProperties", connectionProperties);
        properties.put("openjpa.DynamicEnhancementAgent", "true");
        properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported");

        //            properties.put("openjpa.DataCache", "" + readServerProperties(JPA_CACHE_ENABLED)
        //                    + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
        //            properties.put("openjpa.QueryCache", "" + readServerProperties(JPA_CACHE_ENABLED)
        //                    + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");

        properties.put("openjpa.RemoteCommitProvider", "sjvm");
        properties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO");
        properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
        properties.put("openjpa.jdbc.QuerySQLCache", "false");
        //            properties.put("openjpa.Multithreaded", "true");
        properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72,"
                + " PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
        properties.put("openjpa.RuntimeUnenhancedClasses", "warn");
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    }//from ww  w . jav a 2s.  c o m

    entityManager = factory.createEntityManager();
    return entityManager;
}

From source file:org.apache.ode.dao.jpa.BPELDAOConnectionFactoryImpl.java

@SuppressWarnings("unchecked")
public void init(Properties properties) {
    HashMap<String, Object> propMap = new HashMap<String, Object>();

    //        propMap.put("openjpa.Log", "DefaultLevel=TRACE");
    propMap.put("openjpa.Log", "commons");
    //        propMap.put("openjpa.jdbc.DBDictionary", "org.apache.openjpa.jdbc.sql.DerbyDictionary");

    propMap.put("openjpa.ManagedRuntime", new JpaTxMgrProvider(_tm));
    propMap.put("openjpa.ConnectionFactory", _ds);
    propMap.put("openjpa.ConnectionFactoryMode", "managed");
    //        propMap.put("openjpa.FlushBeforeQueries", "false");
    propMap.put("openjpa.FetchBatchSize", 1000);
    //propMap.put("openjpa.jdbc.TransactionIsolation", "read-committed");

    if (_dbdictionary != null)
        propMap.put("openjpa.jdbc.DBDictionary", _dbdictionary);

    if (properties != null)
        for (Map.Entry me : properties.entrySet())
            propMap.put((String) me.getKey(), me.getValue());

    _emf = Persistence.createEntityManagerFactory("ode-dao", propMap);
}