List of usage examples for javax.persistence EntityManager getEntityManagerFactory
public EntityManagerFactory getEntityManagerFactory();
From source file:org.wildfly.camel.examples.jpa.JPAComponentProducer.java
@Produces @ApplicationScoped//from w ww. j a v a 2 s .co m @Named("jpa") public JpaComponent jpaComponent(PlatformTransactionManager transactionManager, EntityManager entityManager) { JpaComponent component = new JpaComponent(); component.setTransactionManager(transactionManager); component.setEntityManagerFactory(entityManager.getEntityManagerFactory()); return component; }
From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java
@Test public void testPersist() { EntityManagerFactory emf = em.getEntityManagerFactory(); EntityManager em = emf.createEntityManager(); PObject pc = new PObject("XYZ"); em.getTransaction().begin();//from w ww. j av a 2 s .c o m em.persist(pc); em.getTransaction().commit(); Object oid = pc.getId(); em.clear(); // After clean the instance must not be in L1 cache assertFalse(em.contains(pc)); // But it must be found in L2 cache by its OpenJPA identifier assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid))); PObject pc2 = em.find(PObject.class, oid); // After find(), the original instance is not in the L1 cache assertFalse(em.contains(pc)); // After find(), the found instance is in the L1 cache assertTrue(em.contains(pc2)); // The L2 cache must still hold the key assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid))); }
From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java
/** * Deletes ALL entities from the database *///from www . j a v a 2 s. c o m @After public final void deleteAllEntities() { final EntityManager entityManager = getEntityManager(); final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory(); final Metamodel metamodel = entityManagerFactory.getMetamodel(); Set<EntityType<?>> entityTypes = new LinkedHashSet<EntityType<?>>(metamodel.getEntities()); do { final Set<EntityType<?>> failedEntitieTypes = new HashSet<EntityType<?>>(); for (final EntityType<?> entityType : entityTypes) { final String entityClassName = entityType.getBindableJavaType().getName(); try { this.executeInTransaction(new Callable<Object>() { @Override public Object call() throws Exception { logger.trace("Purging all: " + entityClassName); final Query query = entityManager .createQuery("SELECT e FROM " + entityClassName + " AS e"); final List<?> entities = query.getResultList(); logger.trace("Found " + entities.size() + " " + entityClassName + " to delete"); for (final Object entity : entities) { entityManager.remove(entity); } return null; } }); } catch (DataIntegrityViolationException e) { logger.trace( "Failed to delete " + entityClassName + ". Must be a dependency of another entity"); failedEntitieTypes.add(entityType); } } entityTypes = failedEntitieTypes; } while (!entityTypes.isEmpty()); //Reset all spring managed mocks after every test MockitoFactoryBean.resetAllMocks(); }
From source file:facades.PersonFacadeDB.java
@Override public RoleSchool addRole(String json, Integer id) throws NotFoundException { Person p = gson.fromJson(getPerson(id), Person.class); HashMap<String, String> map = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() { }.getType());//from w w w . java2s . c o m String roleName = map.get("roleName"); RoleSchool role; switch (roleName) { case "Teacher Assistant": //Create role RoleSchool ta = new TeacherAssistant(); ta.setPerson(p); role = ta; break; case "Teacher": SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateInString = map.get("date"); Date date = new Date(); try { date = formatter.parse(dateInString); } catch (ParseException e) { e.printStackTrace(System.out); } RoleSchool t = new Teacher(date, map.get("degree")); t.setPerson(p); role = t; break; case "Student": RoleSchool s = new Student(map.get("semester")); s.setPerson(p); role = s; break; default: throw new IllegalArgumentException("no such role"); } //save this info EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); try { em.persist(role); transaction.commit(); em.getEntityManagerFactory().getCache().evictAll(); } catch (Exception e) { throw new NotFoundException("Couldnt add role"); } finally { em.close(); } return role; }
From source file:nl.b3p.viewer.config.services.GeoService.java
public List<Layer> getLayerChildrenCache(Layer l) { if (childrenByParent != null) { EntityManager em = Stripersist.getEntityManager(); if (!em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(l.getChildren())) { List<Layer> childrenList = childrenByParent.get(l); if (childrenList == null) { return Collections.EMPTY_LIST; } else { return childrenList; }/*from w w w . ja v a2 s . c o m*/ } else { return l.getChildren(); } } else { return l.getChildren(); } }
From source file:org.apache.ambari.server.upgrade.AbstractUpgradeCatalog.java
protected void executeInTransaction(Runnable func) { EntityManager entityManager = getEntityManagerProvider().get(); if (entityManager.getTransaction().isActive()) { //already started, reuse func.run();//from www . j av a2s. com } else { entityManager.getTransaction().begin(); try { func.run(); entityManager.getTransaction().commit(); // This is required because some of the entities actively managed by // the persistence context will remain unaware of the actual changes // occurring at the database level. Some UpgradeCatalogs perform // update / delete using CriteriaBuilder directly. entityManager.getEntityManagerFactory().getCache().evictAll(); } catch (Exception e) { LOG.error("Error in transaction ", e); if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw new RuntimeException(e); } } }
From source file:org.eclipse.jubula.client.core.persistence.Persistor.java
/** * Validates the consistency of DbVersion and Jubula Client Version * /*from www . ja va2 s. c om*/ * @param session * current session * @throws PMDatabaseConfException * in case of any problem with db scheme * @throws JBException * in case of a configuration problem * @throws DatabaseVersionConflictException * @throws AmbiguousDatabaseVersionException */ @SuppressWarnings("unchecked") private void validateDBVersion(EntityManager session) throws PMDatabaseConfException, JBException, DatabaseVersionConflictException, AmbiguousDatabaseVersionException { List<DBVersionPO> hits = null; try { hits = session.createQuery("select version from DBVersionPO as version").getResultList(); //$NON-NLS-1$ } catch (RuntimeException e) { // FIXME zeb We were catching a PersistenceException here, but that // does not work for EclipseLink's JPA because they throw // a DatabaseException if something goes wrong with the // database (ex. missing table). We shouldn't have to // worry about catching vendor-specific exceptions, but // it looks like we do. See: // http://stackoverflow.com/questions/2394885/what-exceptions-are-thrown-by-jpa-in-ejb-containers // for a brief discussion on the topic. Throwable cause = ExceptionUtils.getCause(e); if (cause instanceof SQLException) { SQLException se = (SQLException) cause; if (se.getErrorCode() == 17002) { final String msg = Messages.ProblemWithDatabaseSchemeConf + StringConstants.DOT; log.error(msg); throw new PMDatabaseConfException(msg, MessageIDs.E_ERROR_IN_SCHEMA_CONFIG); } } m_newDbSchemeInstalled = installDbScheme(session.getEntityManagerFactory()); try { hits = session.createQuery("select version from DBVersionPO as version").getResultList(); //$NON-NLS-1$ } catch (PersistenceException pe) { final String msg = Messages.ProblemWithInstallingDBScheme + StringConstants.DOT; log.error(msg); throw new PMDatabaseConfException(msg, MessageIDs.E_NO_DB_SCHEME); } catch (DatabaseException dbe) { // FIXME zeb EclipseLink's JPA throws a DatabaseException if // something goes wrong with the database // (ex. missing table), instead of wrapping it in a // PersistenceException. We shouldn't have to // worry about catching vendor-specific exceptions, but // it looks like we do. See: // http://stackoverflow.com/questions/2394885/what-exceptions-are-thrown-by-jpa-in-ejb-containers // for a brief discussion on the topic. final String msg = Messages.ProblemWithInstallingDBScheme + StringConstants.DOT; log.error(msg); throw new PMDatabaseConfException(msg, MessageIDs.E_NO_DB_SCHEME); } } if (!hits.isEmpty() && hits.size() == 1) { DBVersionPO dbVersion = hits.get(0); Integer dbMaj = dbVersion.getMajorVersion(); Integer dbMin = dbVersion.getMinorVersion(); if (dbMaj.equals(IVersion.JB_DB_MAJOR_VERSION)) { if (dbMin.equals(IVersion.JB_DB_MINOR_VERSION)) { log.info(Messages.DBVersion + StringConstants.COLON + StringConstants.SPACE + Messages.OK); } else { log.error(Messages.DBVersion + StringConstants.COLON + StringConstants.SPACE + Messages.MinorVersionInvalid); throw new DatabaseVersionConflictException(dbMaj, dbMin); } } else { log.error(Messages.DBVersion + StringConstants.COLON + StringConstants.SPACE + Messages.MajorVersionInvalid); throw new DatabaseVersionConflictException(dbMaj, dbMin); } } else { log.error(Messages.DBVersion + StringConstants.COLON + StringConstants.SPACE + Messages.DBEntryMissingAmbiguous); throw new AmbiguousDatabaseVersionException(hits); } }