org.datanucleus.api.jdo.JDOPersistenceManagerFactory Java Examples

The following examples show how to use org.datanucleus.api.jdo.JDOPersistenceManagerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void CreateProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Product product = new Product("Tablet", 80.0);
        pm.makePersistent(product);
        Product product2 = new Product("Phone", 20.0);
        pm.makePersistent(product2);
        Product product3 = new Product("Laptop", 200.0);
        pm.makePersistent(product3);
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            double price = rnd.nextDouble();
            Product productx = new Product(nam, price);
            pm.makePersistent(productx);
        }
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #2
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void UpdateProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Query query = pm.newQuery(Product.class, "name == \"Phone\"");
        Collection result = (Collection) query.execute();
        Product product = (Product) result.iterator().next();
        product.setName("Android Phone");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #3
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void DeleteProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Query query = pm.newQuery(Product.class, "name == \"Android Phone\"");
        Collection result = (Collection) query.execute();
        Product product = (Product) result.iterator().next();
        pm.deletePersistent(product);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #4
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void ListProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10");
        List<Product> products = (List<Product>) q.execute();
        Iterator<Product> iter = products.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #5
Source File: PersistenceManagerFactory.java    From Alpine with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    LOGGER.info("Initializing persistence framework");

    final String driverPath = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_DRIVER_PATH);
    if (driverPath != null) {
        final JavaVersion jv = new JavaVersion();
        if (jv.getMajor() > 8) {
            LOGGER.warn("Cannot dynamically expand classpath to include database driver. This capability "
                    + "was removed in Java 11 and higher. Please add the database driver to the classpath "
                    + "when starting the application.");
        } else {
            Config.getInstance().expandClasspath(driverPath);
        }
    }

    pmf = (JDOPersistenceManagerFactory)JDOHelper.getPersistenceManagerFactory(JdoProperties.get(), "Alpine");

    // Ensure that the UpgradeMetaProcessor and SchemaVersion tables are created NOW, not dynamically at runtime.
    final PersistenceNucleusContext ctx = pmf.getNucleusContext();
    final Set<String> classNames = new HashSet<>();
    classNames.add(InstalledUpgrades.class.getCanonicalName());
    classNames.add(SchemaVersion.class.getCanonicalName());
    ((SchemaAwareStoreManager)ctx.getStoreManager()).createSchemaForClasses(classNames, new Properties());
}
 
Example #6
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void listXMLProducts() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        Query q = pm.newQuery("SELECT FROM " + ProductXML.class.getName());
        List<ProductXML> products = (List<ProductXML>) q.execute();
        Iterator<ProductXML> iter = products.iterator();
        while (iter.hasNext()) {
            ProductXML p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.getName(), p.getPrice() });
            pm.deletePersistent(p);
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #7
Source File: GuideToJDO.java    From tutorials with MIT License 6 votes vote down vote up
public void persistXML() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
        pm.makePersistent(productXML);
        ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
        pm.makePersistent(productXML2);
        ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
        pm.makePersistent(productXML3);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}
 
Example #8
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QuerySQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // SQL :
        LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
        Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
        query.setClass(Product.class);
        List<Product> results = query.executeList();

        Iterator<Product> iter = results.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #9
Source File: UpgradeInitializer.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void contextInitialized(final ServletContextEvent event) {
    LOGGER.info("Initializing upgrade framework");

    final String driverPath = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_DRIVER_PATH);
    if (driverPath != null) {
        Config.getInstance().expandClasspath(driverPath);
    }
    final JDOPersistenceManagerFactory pmf  = (JDOPersistenceManagerFactory) JDOHelper.getPersistenceManagerFactory(JdoProperties.get(), "Alpine");

    // Ensure that the UpgradeMetaProcessor and SchemaVersion tables are created NOW, not dynamically at runtime.
    final PersistenceNucleusContext ctx = pmf.getNucleusContext();
    final Set<String> classNames = new HashSet<>();
    classNames.add(InstalledUpgrades.class.getCanonicalName());
    classNames.add(SchemaVersion.class.getCanonicalName());
    ((SchemaAwareStoreManager)ctx.getStoreManager()).createSchemaForClasses(classNames, new Properties());

    if (RequirementsVerifier.failedValidation()) {
        return;
    }
    try (final PersistenceManager pm = pmf.getPersistenceManager();
         final QueryManager qm = new QueryManager(pm)) {
        final UpgradeExecutor executor = new UpgradeExecutor(qm);
        try {
            executor.executeUpgrades(UpgradeItems.getUpgradeItems());
        } catch (UpgradeException e) {
            LOGGER.error("An error occurred performing upgrade processing. " + e.getMessage());
        }
    }
    pmf.close();
}
 
Example #10
Source File: GuideToJDOIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenProduct_WhenNewThenPerformTransaction() {
    PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
    pumd.addClassName("com.baeldung.libraries.jdo.Product");
    pumd.setExcludeUnlistedClasses();
    pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
    pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
    pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
    pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
    pumd.addProperty("datanucleus.autoCreateSchema", "true");
    pumd.addProperty("datanucleus.schema.autoCreateTables", "true");

    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        for (int i = 0; i < 100; i++) {
            String nam = "Product-" + i;
            Product productx = new Product(nam, (double) i);
            pm.makePersistent(productx);
        }
        tx.commit();
    } catch (Throwable thr) {
        fail("Failed test : " + thr.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }

    pmf.close();
}
 
Example #11
Source File: MyApp.java    From tutorials with MIT License 5 votes vote down vote up
public static void defineDynamicPersistentUnit() {

        PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
        pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
        pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
        pumd.addProperty("datanucleus.xml.indentSize", "4");

        pmf = new JDOPersistenceManagerFactory(pumd, null);
        pm = pmf.getPersistenceManager();
    }
 
Example #12
Source File: MyApp.java    From tutorials with MIT License 5 votes vote down vote up
public static void defineDynamicPersistentUnit() {

        PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
        pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
        pumd.addProperty("javax.jdo.option.ConnectionUserName", "root");
        pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin");
        pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver");
        pumd.addProperty("datanucleus.schema.autoCreateAll", "true");

        pmf = new JDOPersistenceManagerFactory(pumd, null);
        pm = pmf.getPersistenceManager();
    }
 
Example #13
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJPQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // JPQL :
        LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------");
        Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
        List results = (List) q.execute();

        Iterator<Product> iter = results.iterator();
        while (iter.hasNext()) {
            Product p = iter.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #14
Source File: GuideToJDO.java    From tutorials with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void QueryJDOQL() {
    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();

        // Declarative JDOQL :
        LOGGER.log(Level.INFO, "Declarative JDOQL --------------------------------------------------------------");
        Query qDJDOQL = pm.newQuery(Product.class);
        qDJDOQL.setFilter("name == 'Tablet' && price == price_value");
        qDJDOQL.declareParameters("double price_value");
        List<Product> resultsqDJDOQL = qDJDOQL.setParameters(80.0).executeList();

        Iterator<Product> iterDJDOQL = resultsqDJDOQL.iterator();
        while (iterDJDOQL.hasNext()) {
            Product p = iterDJDOQL.next();
            LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
        }
        LOGGER.log(Level.INFO, "--------------------------------------------------------------");

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }

        pm.close();
    }
}
 
Example #15
Source File: HivePersistenceManagerFactory.java    From metacat with Apache License 2.0 5 votes vote down vote up
private static synchronized PersistenceManagerFactory getpersistencemanagerfactory(final Map props) {
    final String name = String.valueOf(props.get(HiveConfigConstants.JAVAX_JDO_OPTION_NAME));
    PersistenceManagerFactory result = factories.get(name);
    if (result == null) {
        final DataSource dataSource = DataSourceManager.get().get(name);
        final Map<String, Object> properties = Maps.newHashMap();
        properties.put(HiveConfigConstants.DATANUCLEUS_FIXEDDATASTORE,
            props.get(HiveConfigConstants.DATANUCLEUS_FIXEDDATASTORE));
        properties.put(HiveConfigConstants.DATANUCLEUS_AUTOCREATESCHEMA,
            props.get(HiveConfigConstants.DATANUCLEUS_AUTOCREATESCHEMA));
        properties.put(HiveConfigConstants.DATANUCLEUS_IDENTIFIERFACTORY,
            HiveConfigConstants.DATANUCLEUS_DATANUCLEU1);
        properties.put(HiveConfigConstants.DATANUCLEUS_CONNECTIONFACTORY, dataSource);
        properties.put(HiveConfigConstants.DATANUCLEUS_RDBMS_USELEGACYNATIVEVALUESTRATEGY, true);
        properties.put(HiveConfigConstants.DATANUCLEUS_TRANSACTIONISOLATION,
            HiveConfigConstants.DATANUCLEUS_READCOMMITTED);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATETABLE, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATECONSTRAINTS, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_VALIDATECOLUMNS, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_CACHE_LEVEL2, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_CACHE_LEVEL2_TYPE, "none");
        properties.put(HiveConfigConstants.DATANUCLEUS_PERSISTENCYBYREACHATCOMMIT, false);
        properties.put(HiveConfigConstants.DATANUCLEUS_AUTOSTARTMECHANISMMODE, "Checked");
        properties.put(HiveConfigConstants.DATANUCLEUS_DETACHALLONCOMMIT, true);
        properties.put(HiveConfigConstants.DATANUCLEUS_DETACHALLONROLLBACK, true);
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTORETIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTORETIMEOUT));
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTOREREADTIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTOREREADTIMEOUT));
        properties.put(HiveConfigConstants.JAVAX_JDO_DATASTOREWRITETIMEOUT,
            props.get(HiveConfigConstants.JAVAX_JDO_DATASTOREWRITETIMEOUT));
        result = JDOPersistenceManagerFactory.getPersistenceManagerFactory(properties);
        factories.put(name, result);
    }
    return result;
}
 
Example #16
Source File: DbUtil.java    From Alpine with Apache License 2.0 5 votes vote down vote up
public static void createTable(AbstractAlpineQueryManager qm, Class... classes) {
    JDOPersistenceManagerFactory pmf = (JDOPersistenceManagerFactory) qm.getPersistenceManager().getPersistenceManagerFactory();
    final PersistenceNucleusContext ctx = pmf.getNucleusContext();
    final Set<String> classNames = new HashSet<>();
    for (Class clazz: classes) {
        classNames.add(clazz.getCanonicalName());
    }
    ((SchemaAwareStoreManager)ctx.getStoreManager()).createSchemaForClasses(classNames, new Properties());
}
 
Example #17
Source File: PersistenceManagerFactory.java    From Alpine with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JDO PersistenceManager.
 * @return a PersistenceManager
 */
public static PersistenceManager createPersistenceManager() {
    if (Config.isUnitTestsEnabled()) {
        pmf = (JDOPersistenceManagerFactory)JDOHelper.getPersistenceManagerFactory(JdoProperties.unit(), "Alpine");
    }
    if (pmf == null) {
        throw new IllegalStateException("Context is not initialized yet.");
    }
    return pmf.getPersistenceManager();
}
 
Example #18
Source File: GuideToJDOIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenProduct_WhenQueryThenExist() {
    PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
    pumd.addClassName("com.baeldung.libraries.jdo.Product");
    pumd.setExcludeUnlistedClasses();
    pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver");
    pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
    pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
    pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
    pumd.addProperty("datanucleus.autoCreateSchema", "true");
    pumd.addProperty("datanucleus.schema.autoCreateTables", "true");

    PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
        tx.begin();
        Product product = new Product("Tablet", 80.0);
        pm.makePersistent(product);
        Product product2 = new Product("Phone", 20.0);
        pm.makePersistent(product2);
        Product product3 = new Product("Laptop", 200.0);
        pm.makePersistent(product3);
        tx.commit();
    } catch (Throwable thr) {
        fail("Failed test : " + thr.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }

    pmf.close();

    PersistenceManagerFactory pmf2 = new JDOPersistenceManagerFactory(pumd, null);
    PersistenceManager pm2 = pmf2.getPersistenceManager();
    Transaction tx2 = pm2.currentTransaction();
    try {
        tx2.begin();

        @SuppressWarnings("rawtypes")
        Query q = pm2.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price == 200");
        @SuppressWarnings("unchecked")
        List<Product> products = (List<Product>) q.execute();
        for (Product p : products) {
            assertEquals("Laptop", p.name);
        }

        tx2.commit();
    } finally {
        if (tx2.isActive()) {
            tx2.rollback();
        }

        pm2.close();
    }
}