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.apache.airavata.registry.core.replica.catalog.utils.ReplicaCatalogJPAUtils.java

public static EntityManager getEntityManager() throws ApplicationSettingsException {
    if (factory == null) {
        String connectionProperties = "DriverClassName=" + readServerProperties(REPLICACATALOG_JDBC_DRIVER)
                + "," + "Url=" + readServerProperties(REPLICACATALOG_JDBC_URL) + "?autoReconnect=true,"
                + "Username=" + readServerProperties(REPLICACATALOG_JDBC_USER) + "," + "Password="
                + readServerProperties(REPLICACATALOG_JDBC_PWD) + ",validationQuery="
                + readServerProperties(REPLICACATALOG_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");
        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  va  2 s .  c om*/
    dataCatEntityManager = factory.createEntityManager();
    return dataCatEntityManager;
}

From source file:io.symcpe.hendrix.api.dao.TestTemplateManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);/* w  ww.j a  v a  2s .c o m*/
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("hendrix", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    EntityManager em = emf.createEntityManager();

    Tenant tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_1);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    em.close();
}

From source file:com.yahoo.sql4d.indexeragent.meta.DBHandler.java

public DBHandler() {
    String host = getHost();/*from   w w w  .j  a v a  2  s  .  c  om*/
    int port = getPort();
    String id = getId();
    String password = getPassword();
    String dbName = getDbName();
    String dbType = getDbType();

    String connectUrl, dialect, driver;

    switch (dbType) {
    case "mysql":
        connectUrl = String.format("jdbc:mysql://%s:%d/%s?autoReconnectForPools=true", host, port, dbName);
        driver = "com.mysql.jdbc.Driver";
        dialect = "org.hibernate.dialect.MySQLDialect";
        break;
    case "derby":
    default:
        connectUrl = String.format("jdbc:derby://%s:%d/%s;create=true", host, port, dbName);
        driver = "org.apache.derby.jdbc.ClientDriver";
        dialect = "org.hibernate.dialect.DerbyDialect";
    }

    Map<String, String> configOverride = ImmutableMap.of("javax.persistence.jdbc.url", connectUrl,
            "javax.persistence.jdbc.user", id, "javax.persistence.jdbc.password", password, "hibernate.dialect",
            dialect, "javax.persistence.jdbc.driver", driver);
    log.info("Overriding database configuration : {}", configOverride);
    emFactory = Persistence.createEntityManagerFactory("indexerAgent", configOverride);
}

From source file:org.apache.james.modules.data.JPAEntityManagerModule.java

@Provides
@Singleton/*from ww  w  .  j av  a 2 s.c o m*/
public EntityManagerFactory provideEntityManagerFactory(JPAConfiguration jpaConfiguration) {
    HashMap<String, String> properties = new HashMap<>();

    properties.put("openjpa.ConnectionDriverName", jpaConfiguration.getDriverName());
    properties.put("openjpa.ConnectionURL", jpaConfiguration.getDriverURL());

    List<String> connectionFactoryProperties = new ArrayList<>();
    connectionFactoryProperties.add("TestOnBorrow=" + jpaConfiguration.isTestOnBorrow());
    if (jpaConfiguration.getValidationQueryTimeoutSec() > 0) {
        connectionFactoryProperties
                .add("ValidationTimeout=" + jpaConfiguration.getValidationQueryTimeoutSec() * 1000);
    }
    if (jpaConfiguration.getValidationQuery() != null) {
        connectionFactoryProperties.add("ValidationSQL='" + jpaConfiguration.getValidationQuery() + "'");
    }
    properties.put("openjpa.ConnectionFactoryProperties", Joiner.on(", ").join(connectionFactoryProperties));

    return Persistence.createEntityManagerFactory("Global", properties);
}

From source file:com.srotya.tau.api.dao.TestTemplateManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);/*w w w .  j  ava2 s.  c  om*/
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("tau", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    EntityManager em = emf.createEntityManager();

    RuleGroup ruleGroup = new RuleGroup();
    ruleGroup.setRuleGroupId(RULE_GROUP_ID_1);
    ruleGroup.setRuleGroupName(TEST_RULE_GROUP);
    RuleGroupManager.getInstance().createRuleGroup(em, ruleGroup);

    em.close();
}

From source file:org.apache.airavata.registry.core.experiment.catalog.ExpCatResourceUtils.java

public static EntityManager getEntityManager() throws ExperimentCatalogException {
    EntityManager expCatEntityManager;//from w  w w.j  a  va 2 s.c o m
    if (expCatFactory == null) {
        String connectionProperties = "DriverClassName=" + Utils.getJDBCDriver() + "," + "Url="
                + Utils.getJDBCURL() + "?autoReconnect=true," + "Username=" + Utils.getJDBCUser() + ","
                + "Password=" + Utils.getJDBCPassword() + ",validationQuery=" + Utils.getValidationQuery();
        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");
        //            properties.put("openjpa.DataCache","" + Utils.isCachingEnabled() + "(CacheSize=" + Utils.getJPACacheSize() + ", SoftReferenceSize=0)");
        //            properties.put("openjpa.QueryCache","" + Utils.isCachingEnabled() + "(CacheSize=" + Utils.getJPACacheSize() + ", SoftReferenceSize=0)");
        //            properties.put("javax.persistence.sharedCache.mode","ALL");
        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.ConnectionFactoryProperties",
                "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
        //         properties.put("openjpa.jdbc.QuerySQLCache", "false");
        if (expCatFactory == null) {
            expCatFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
        }
    }
    expCatEntityManager = expCatFactory.createEntityManager();
    return expCatEntityManager;
}

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

public synchronized EntityManagerFactory create(File database) throws MetadataException {
    EntityManagerFactory factory;/*from   w  ww  . j  av a2  s  . c  o m*/
    String name = "metadata";
    Hashtable<String, String> persistProperties = new Hashtable<String, String>();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    // This swallow all the output log from derby.
    System.setProperty("derby.stream.error.field",
            "com.nokia.helium.metadata.DerbyFactoryManagerCreator.DEV_NULL");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database.getAbsolutePath());
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    if (database.exists()) {
        if (!checkDatabaseIntegrity(database)) {
            try {
                FileUtils.forceDelete(database);
            } catch (java.io.IOException iex) {
                throw new MetadataException("Failed deleting corrupted db: " + iex, iex);
            }
        } else {
            return Persistence.createEntityManagerFactory(name, persistProperties);
        }
    }
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    factory = Persistence.createEntityManagerFactory(name, persistProperties);
    EntityManager entityManager = factory.createEntityManager();
    // Pushing default data into the current schema
    try {
        entityManager.getTransaction().begin();
        // Version of the schema is pushed.
        entityManager.persist(new Version());
        // Default set of severity is pushed.
        for (SeverityEnum.Severity severity : SeverityEnum.Severity.values()) {
            Severity pData = new Severity();
            pData.setSeverity(severity.toString());
            entityManager.persist(pData);
        }
        entityManager.getTransaction().commit();
    } finally {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
            entityManager.clear();
        }
        entityManager.close();
    }
    return factory;
}

From source file:org.apache.airavata.persistance.registry.jpa.ResourceUtils.java

public static EntityManager getEntityManager() {
    if (factory == null) {
        String connectionProperties = "DriverClassName=" + Utils.getJDBCDriver() + "," + "Url="
                + Utils.getJDBCURL() + "," + "Username=" + Utils.getJDBCUser() + "," + "Password="
                + Utils.getJDBCPassword() + ",validationQuery=" + Utils.getValidationQuery();
        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");
        properties.put("openjpa.DataCache",
                "true(CacheSize=" + Utils.getJPACacheSize() + ", SoftReferenceSize=0)");
        properties.put("openjpa.QueryCache",
                "true(CacheSize=" + Utils.getJPACacheSize() + ", SoftReferenceSize=0)");
        properties.put("openjpa.RemoteCommitProvider", "sjvm");
        properties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO");
        properties.put("openjpa.jdbc.DBDictionary", "SupportsMultipleNontransactionalResultSets=false");
        //            properties.put("openjpa.ReadLockLevel", "none");
        //            properties.put("openjpa.WriteLockLevel", "none");
        //            properties.put("openjpa.LockTimeout", "30000");
        //            properties.put("openjpa.LockManager", "none");
        properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
        //            properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=60000");
        properties.put("openjpa.jdbc.QuerySQLCache", "false");
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    }/*w w w . ja  v a 2  s . com*/
    return factory.createEntityManager();
}

From source file:com.nokia.helium.jpa.ORMEntityManager.java

/**  
 * Constructor.//w  ww .j av  a  2s  .  c  o  m
 * @param urlPath path for which entity manager to be
 * created.
 */
@SuppressWarnings("unchecked")
public ORMEntityManager(String urlPath) throws Exception {
    String name = "metadata";
    Hashtable persistProperties = new Hashtable();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + urlPath);
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    File dbFile = new File(urlPath);
    commitCountObject = new ORMCommitCount();
    if (dbFile.exists()) {
        try {
            log.debug("checking db integrity for :" + urlPath);
            if (!checkDatabaseIntegrity(urlPath)) {
                log.debug("db integrity failed cleaning up old db");
                try {
                    log.debug("deleting the url path" + urlPath);
                    FileUtils.forceDelete(dbFile);
                    log.debug("successfully removed the urlpath" + urlPath);
                } catch (java.io.IOException iex) {
                    log.debug("deleting the db directory failed", iex);
                    throw new BuildException("failed deleting corrupted db", iex);
                }
            } else {
                log.debug("db exists and trying to create entity manager");
                EntityManagerFactory factory = Persistence.createEntityManagerFactory(name, persistProperties);
                entityManager = factory.createEntityManager();
                entityManager.getTransaction().begin();
                return;
            }
        } catch (Exception ex) {
            log.debug("Failed to open the database, might be corrupted, creating new db", ex);
            try {
                FileUtils.deleteDirectory(dbFile);
            } catch (java.io.IOException iex) {
                log.debug("deleting the db directory failed");
                throw iex;
            }
        }
    }
    log.debug("url path not exists" + urlPath + "creating it");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + urlPath + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    EntityManagerFactory factory = Persistence.createEntityManagerFactory(name, persistProperties);
    entityManager = factory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(new Version());
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityManager.getTransaction().begin();
}

From source file:com.impetus.client.crud.datatypes.ByteDataTest.java

/**
 * Sets the up./*from w  w w .  j  a v a  2s.c o  m*/
 * 
 * @throws Exception
 *             the exception
 */
@Before
public void setUp() throws Exception {

    CassandraCli.cassandraSetUp();
    CassandraCli.createKeySpace("KunderaExamples");

    if (propertyMap == null) {
        propertyMap = new HashMap();
        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, "create");
    }
    propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);

    emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);
    em = emf.createEntityManager();
    col = new java.util.HashMap<Object, Object>();
}