Java Code Examples for javax.jdo.PersistenceManagerFactory#getPersistenceManager()

The following examples show how to use javax.jdo.PersistenceManagerFactory#getPersistenceManager() . 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: JDOPMRetriever.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
public  Object getPersistenceManager(String client,PersistenceManagerFactory pmf) 
{
	Map<String,PersistenceManager> map = (Map<String,PersistenceManager>)super.get();
	PersistenceManager pm = null;
	if (map != null)
		pm = map.get(client);
	
    if(pm == null || pm.isClosed()) 
    {
        pm = pmf.getPersistenceManager( ); 
        pm.setUserObject(client);
        if (map == null)
        	map = new HashMap<>();
        map.put(client, pm);
        set(map);
    }

    return pm;
}
 
Example 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * <p>Same as {@code getPersistenceManager}, but throwing the original JDOException.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager
 * @throws JDOException if the PersistenceManager couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean)
 * @see JdoTransactionManager
 */
public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
	throws JDOException, IllegalStateException {

	Assert.notNull(pmf, "No PersistenceManagerFactory specified");

	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null) {
		if (!pmHolder.isSynchronizedWithTransaction() &&
				TransactionSynchronizationManager.isSynchronizationActive()) {
			pmHolder.setSynchronizedWithTransaction(true);
			TransactionSynchronizationManager.registerSynchronization(
					new PersistenceManagerSynchronization(pmHolder, pmf, false));
		}
		return pmHolder.getPersistenceManager();
	}

	if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
		throw new IllegalStateException("No JDO PersistenceManager bound to thread, " +
				"and configuration does not allow creation of non-transactional one here");
	}

	logger.debug("Opening JDO PersistenceManager");
	PersistenceManager pm = pmf.getPersistenceManager();

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering transaction synchronization for JDO PersistenceManager");
		// Use same PersistenceManager for further JDO actions within the transaction.
		// Thread object will get removed by synchronization at transaction completion.
		pmHolder = new PersistenceManagerHolder(pm);
		pmHolder.setSynchronizedWithTransaction(true);
		TransactionSynchronizationManager.registerSynchronization(
				new PersistenceManagerSynchronization(pmHolder, pmf, true));
		TransactionSynchronizationManager.bindResource(pmf, pmHolder);
	}

	return pm;
}
 
Example 9
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 10
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 11
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 12
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 13
Source File: PersistenceManagerFactoryUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtain a JDO PersistenceManager via the given factory. Is aware of a
 * corresponding PersistenceManager bound to the current thread,
 * for example when using JdoTransactionManager. Will create a new
 * PersistenceManager else, if "allowCreate" is {@code true}.
 * <p>Same as {@code getPersistenceManager}, but throwing the original JDOException.
 * @param pmf PersistenceManagerFactory to create the PersistenceManager with
 * @param allowCreate if a non-transactional PersistenceManager should be created
 * when no transactional PersistenceManager can be found for the current thread
 * @return the PersistenceManager
 * @throws JDOException if the PersistenceManager couldn't be created
 * @throws IllegalStateException if no thread-bound PersistenceManager found and
 * "allowCreate" is {@code false}
 * @see #getPersistenceManager(javax.jdo.PersistenceManagerFactory, boolean)
 * @see JdoTransactionManager
 */
public static PersistenceManager doGetPersistenceManager(PersistenceManagerFactory pmf, boolean allowCreate)
	throws JDOException, IllegalStateException {

	Assert.notNull(pmf, "No PersistenceManagerFactory specified");

	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null) {
		if (!pmHolder.isSynchronizedWithTransaction() &&
				TransactionSynchronizationManager.isSynchronizationActive()) {
			pmHolder.setSynchronizedWithTransaction(true);
			TransactionSynchronizationManager.registerSynchronization(
					new PersistenceManagerSynchronization(pmHolder, pmf, false));
		}
		return pmHolder.getPersistenceManager();
	}

	if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
		throw new IllegalStateException("No JDO PersistenceManager bound to thread, " +
				"and configuration does not allow creation of non-transactional one here");
	}

	logger.debug("Opening JDO PersistenceManager");
	PersistenceManager pm = pmf.getPersistenceManager();

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering transaction synchronization for JDO PersistenceManager");
		// Use same PersistenceManager for further JDO actions within the transaction.
		// Thread object will get removed by synchronization at transaction completion.
		pmHolder = new PersistenceManagerHolder(pm);
		pmHolder.setSynchronizedWithTransaction(true);
		TransactionSynchronizationManager.registerSynchronization(
				new PersistenceManagerSynchronization(pmHolder, pmf, true));
		TransactionSynchronizationManager.bindResource(pmf, pmHolder);
	}

	return pm;
}
 
Example 14
Source File: JDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public PersistenceManager getPersistenceManager() {
  final PersistenceManagerFactory emf = getPersistenceManagerFactory();
  return emf.getPersistenceManager();
}
 
Example 15
Source File: JDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public PersistenceManager getPersistenceManager() {
  final PersistenceManagerFactory emf = getPersistenceManagerFactory();
  return emf.getPersistenceManager();
}
 
Example 16
Source File: AbstractJDOTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public PersistenceManager createPersistenceManager() {
  final PersistenceManagerFactory emf = getPersistenceManagerFactory();
  return emf.getPersistenceManager();
}
 
Example 17
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();
    }
}