List of usage examples for javax.persistence EntityManagerFactory createEntityManager
public EntityManager createEntityManager();
EntityManager
. From source file:org.apache.openjpa.conf.TestBadJdbcUrl.java
/** * Attempts to connect with given properties and analyze exception for the * existence of given target exception and error message strings. * /*w w w . j a v a2 s . c o m*/ * @param props * the properties to initialize the persistence unit * @param target * the type expected exception to be raised. * @param nested * the type expected nested exception. null implies not to look * for any. * @param keys * the strings that must occur in the exception message. */ private void verifyConnectException(Properties props, Class targetType, Class nestedType, String... keys) { EntityManagerFactory emf = null; EntityManager em = null; try { emf = Persistence.createEntityManagerFactory("test", props); em = emf.createEntityManager(); OpenJPAPersistence.cast(em).getConnection(); fail("Should have caught a " + targetType.getName()); } catch (Throwable t) { assertException(t, targetType, nestedType); assertMessage(t, keys); } finally { if (em != null) em.close(); if (emf != null) emf.close(); } }
From source file:org.compass.gps.device.jpa.entities.TopLinkEssentialsJpaEntitiesLocator.java
public EntityInformation[] locate(EntityManagerFactory entityManagerFactory, JpaGpsDevice device) throws JpaGpsDeviceException { CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps(); EntityManager entityManager = (EntityManager) entityManagerFactory.createEntityManager(); Session session = entityManager.getServerSession(); entityManager.close();//from w w w . ja v a 2 s .c o m ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>(); Map descriptors = session.getDescriptors(); for (Object o : descriptors.values()) { ClassDescriptor classDescriptor = (ClassDescriptor) o; String entityname = classDescriptor.getJavaClassName(); if (!gps.hasMappingForEntityForIndex((entityname))) { if (log.isDebugEnabled()) { log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out"); } continue; } if (shouldFilter(entityname, classDescriptor, device)) { continue; } Class<?> clazz = classDescriptor.getJavaClass(); ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname); EntityInformation entityInformation = new EntityInformation(clazz, classDescriptor.getAlias(), resourceMapping.getSubIndexHash().getSubIndexes()); entitiesList.add(entityInformation); if (log.isDebugEnabled()) { log.debug("Entity [" + entityname + "] will be indexed"); } } return entitiesList.toArray(new EntityInformation[entitiesList.size()]); }
From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java
@Test public void testClearCache() { EntityManagerFactory emf = em.getEntityManagerFactory(); EntityManager entityManager = emf.createEntityManager(); EntityTransaction tx = entityManager.getTransaction(); tx.begin();//from ww w . j a v a 2 s . co m SubQObject subQObject = new SubQObject("one", "two"); QObject qObject = new QObject("one"); PObject pObject = new PObject("one"); entityManager.persist(subQObject); entityManager.persist(qObject); entityManager.persist(pObject); tx.commit(); assertTrue(getCache(subQObject.getClass()).contains(getOpenJPAId(subQObject, subQObject.getId()))); assertTrue(getCache(qObject.getClass()).contains(getOpenJPAId(qObject, qObject.getId()))); assertTrue(getCache(pObject.getClass()).contains(getOpenJPAId(pObject, pObject.getId()))); evictAllOfType(qObject.getClass(), false); assertFalse("QObject entries should be all gone", OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId())); assertTrue("SubQObject entries should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId())); assertTrue("This PObject object should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId())); tx = entityManager.getTransaction(); tx.begin(); qObject = new QObject("two"); entityManager.persist(qObject); tx.commit(); evictAllOfType(qObject.getClass(), true); assertFalse("QObject entries should be all gone", OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId())); assertFalse("SubQObject entries should be all gone", OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId())); assertTrue("This PObject object should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId())); tx = entityManager.getTransaction(); tx.begin(); qObject = new QObject("three"); entityManager.persist(qObject); subQObject = new SubQObject("two", "two"); entityManager.persist(subQObject); tx.commit(); evictAllOfType(subQObject.getClass(), false); assertTrue("QObject entries should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId())); assertFalse("SubQObject entries should be all gone", OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId())); assertTrue("This PObject object should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId())); tx = entityManager.getTransaction(); tx.begin(); subQObject = new SubQObject("three", "three"); entityManager.persist(subQObject); tx.commit(); evictAllOfType(pObject.getClass(), true); assertTrue("QObject entries should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId())); assertTrue("SubQObject entries should still be in the cache", OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId())); assertFalse("This PObject object should be gone", OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId())); }
From source file:org.compass.gps.device.jpa.entities.EclipseLinkJpaEntitiesLocator.java
public EntityInformation[] locate(EntityManagerFactory entityManagerFactory, JpaGpsDevice device) throws JpaGpsDeviceException { CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps(); JpaEntityManager entityManager = (JpaEntityManager) entityManagerFactory.createEntityManager(); Session session = entityManager.getServerSession(); entityManager.close();/*from ww w. j a v a2s . c o m*/ ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>(); Map descriptors = session.getDescriptors(); for (Object o : descriptors.values()) { ClassDescriptor classDescriptor = (ClassDescriptor) o; String entityname = classDescriptor.getJavaClassName(); if (!gps.hasMappingForEntityForIndex((entityname))) { if (log.isDebugEnabled()) { log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out"); } continue; } if (shouldFilter(entityname, classDescriptor, device)) { continue; } Class<?> clazz = classDescriptor.getJavaClass(); ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname); EntityInformation entityInformation = new EntityInformation(clazz, classDescriptor.getAlias(), resourceMapping.getSubIndexHash().getSubIndexes()); entitiesList.add(entityInformation); if (log.isDebugEnabled()) { log.debug("Entity [" + entityname + "] will be indexed"); } } return entitiesList.toArray(new EntityInformation[entitiesList.size()]); }
From source file:org.eclipse.skalli.services.persistence.EntityManagerServiceBase.java
private EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) throws StorageException { try {// ww w. j a va 2s . co m return entityManagerFactory.createEntityManager(); } catch (IllegalStateException e) { throw new StorageException(MessageFormat.format("Failed to create an entity manager using factory {0}", entityManagerFactory.getClass()), e); } }
From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java
@Test @PerfTest(invocations = 10)// www . j a va 2s . co 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:com.nokia.helium.jpa.ORMEntityManager.java
/** * Constructor./*from w w w .ja va2s.c om*/ * @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.boylesoftware.web.impl.auth.AbstractUserRecordHandler.java
@Override public T getUser(final int id, final int salt, final EntityManagerFactory emf) { final boolean debug = this.log.isDebugEnabled(); if (debug) {// w w w .java2 s . c o m this.log.debug("looking up user id " + id + ", salt " + salt + " in the database"); this.log.debug("creating entity manager"); } final EntityManager em = emf.createEntityManager(); try { final T user = em.find(this.userRecordClass, Integer.valueOf(id)); if ((user == null) || (this.getUserSalt(user) != salt)) { if (debug) this.log.debug("user not found or salt does not match"); return null; } if (debug) this.log.debug("user found"); return user; } finally { if (debug) this.log.debug("closing entity manager"); em.close(); } }
From source file:BO.UserHandler.java
public boolean updateDeviceToken(VUser u) { EntityManager em;/*from w ww. java 2 s .co m*/ EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); System.out.println("Updating token: " + u.getDeviceToken()); try { em.getTransaction().begin(); User user; user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email") .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult(); user.setDeviceToken(u.getDeviceToken()); em.persist(user); em.flush(); em.getTransaction().commit(); return true; } catch (NoResultException e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:BO.UserHandler.java
private User getUserByEmail(String email) { User tempUser;// w w w . j a va 2 s . c o m EntityManager em; EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { tempUser = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email") .setParameter("email", email).getSingleResult(); return tempUser; } catch (NoResultException e) { throw (e); } catch (Exception e) { throw (e); } finally { if (em != null) { em.close(); } if (emf != null) { emf.close(); } } }