javax.persistence.EntityTransaction#isActive ( )源码实例Demo

下面列出了javax.persistence.EntityTransaction#isActive ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hibernate-master-class   文件: AbstractTest.java
protected <T> T doInJPA(JPATransactionFunction<T> function) {
    T result = null;
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
        entityManager = emf.createEntityManager();
        function.beforeTransactionCompletion();
        txn = entityManager.getTransaction();
        txn.begin();
        result = function.apply(entityManager);
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive()) txn.rollback();
        throw e;
    } finally {
        function.afterTransactionCompletion();
        if (entityManager != null) {
            entityManager.close();
        }
    }
    return result;
}
 
private static void persistEntities() {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         em.persist(new Event("Caught a pokemon!"));
         em.persist(new Event("Hatched an egg"));
         em.persist(new Event("Became a gym leader"));
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
源代码3 项目: james-project   文件: TransactionRunner.java
public <T> T runAndRetrieveResult(Function<EntityManager, T> toResult,
                                  Function<PersistenceException, T> errorHandler) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        T result = toResult.apply(entityManager);
        transaction.commit();
        return result;
    } catch (PersistenceException e) {
        LOGGER.warn("Could not execute transaction", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        return errorHandler.apply(e);
    } finally {
        EntityManagerUtils.safelyClose(entityManager);
    }
}
 
源代码4 项目: ranger   文件: DBAuditDestination.java
private boolean commitTransaction() {
	boolean ret = false;
	EntityTransaction trx = null;

	try {
		trx = getTransaction();

		if (trx != null && trx.isActive()) {
			trx.commit();
			ret = true;
		} else {
			throw new Exception("trx is null or not active");
		}
	} catch (Throwable excp) {
		logger.error("DBAuditDestination.commitTransaction(): failed", excp);

		cleanUp(); // so that next insert will try to init()
	} finally {
		clearEntityManager();
	}

	return ret;
}
 
源代码5 项目: quarkus   文件: JPAFunctionalityTestEndpoint.java
private static void verifyHqlFetch(EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();

            em.createQuery("from Person p left join fetch p.address a").getResultList();

            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }
    } finally {
        em.close();
    }
}
 
源代码6 项目: juddi   文件: LdapSimpleAuthenticator.java
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
 
源代码7 项目: pnc   文件: ModelValidationTest.java
@Test
public void testProductVersionStringValidationFailureOnCommit() throws Exception {

    ProductVersion productVersion1 = ProductVersion.Builder.newBuilder()
            .product(Product.Builder.newBuilder().id(1).build())
            .version("foo") // Invalid version string
            .build();

    EntityManager em = getEmFactory().createEntityManager();
    EntityTransaction tx1 = em.getTransaction();

    try {
        tx1.begin();
        em.persist(productVersion1);
        tx1.commit(); // This should throw a Rollback exception caused by the constraint violation

    } catch (RollbackException e) {
        if (tx1 != null && tx1.isActive()) {
            tx1.rollback();
        }
        Assert.assertTrue(e.getCause() instanceof ConstraintViolationException);
    } finally {
        em.close();
    }

}
 
private static void deleteEntity(long id) {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         Event event = em.find(Event.class, id);
         em.remove(event);
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
源代码9 项目: james-project   文件: JPASubscriptionMapper.java
@Override
public void delete(Subscription subscription) throws SubscriptionException {
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    boolean localTransaction = !transaction.isActive();
    if (localTransaction) {
        transaction.begin();
    }
    try {
        findJpaSubscription(entityManager, subscription)
            .ifPresent(entityManager::remove);
        if (localTransaction) {
            if (transaction.isActive()) {
                transaction.commit();
            }
        }
    } catch (PersistenceException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new SubscriptionException(e);
    }
}
 
源代码10 项目: Truck-Factor   文件: NewFileInfoDAO.java
public int updateLanguageFileInfo(String projectName, String language, List<String> paths) {
	FileType fileType = FileType.getType(language);
	List<Query> queries = new ArrayList<Query>();
	for (String path : paths) {			
		if (path.contains("\'"))
			path = path.replace("'", "''");
		String hql = "UPDATE  newfileinfo "
				+ "SET kind = \'"
				+ fileType
				+ "\'  , language = \'"
				+ language
				+ "\', filtered = \'FALSE\' "
				+ ", filterinfo = \'\' "
				+ "WHERE repositoryname = \'" + projectName + "\' AND path =  \'"
				+ path + "\' " + ";";
		queries.add(em.createNativeQuery(hql));
	}
	int rows =0 ;
	EntityTransaction tx = this.em.getTransaction();
	try {
		tx.begin();
		for (Query query : queries) {
			rows += query.executeUpdate();
		}			
		tx.commit();
	} catch (RuntimeException e) {
		if(tx != null && tx.isActive()) 
			tx.rollback();
		throw e;
	} 
	finally{
		this.em.clear();
	}
	return rows;
	
}
 
源代码11 项目: Truck-Factor   文件: NewFileInfoDAO.java
public int filterAndUpdateFilesInfoByLanguage(String whereClauses, String filterStamp){
	String custom = "";
	     
	String hql = "UPDATE  newfileinfo AS fi "
			+ "SET filtered = \'TRUE\', filterinfo = \'"+ filterStamp +"\'  "
			+ "FROM projectinfo AS pi    "
			+ "WHERE pi.fullname = fi.repositoryname AND "
			+ whereClauses
			+ ";";
			
			
	Query q = em.createNativeQuery(hql);
	int rows =0 ;
	EntityTransaction tx = this.em.getTransaction();
	try {
		tx.begin();
		rows = q.executeUpdate();
		tx.commit();
	} catch (RuntimeException e) {
		if(tx != null && tx.isActive()) 
			tx.rollback();
		throw e;
	} 
	finally{
		this.em.clear();
	}
	return rows;
		
}
 
源代码12 项目: juddi   文件: ValidateValueSetValidation.java
/**
 * return the publisher
 *
 * @param tmodelKey
 * @return
 * @throws ValueNotAllowedException
 */
public static TModel GetTModel_API_IfExists(String tmodelKey) throws ValueNotAllowedException {
        EntityManager em = PersistenceManager.getEntityManager();

        TModel apitmodel = null;
        if (em == null) {
                //this is normally the Install class firing up
                log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
                return null;
        } else {


                EntityTransaction tx = em.getTransaction();
                try {
                        Tmodel modelTModel = null;
                        tx.begin();
                        modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
                        if (modelTModel != null) {
                                apitmodel = new TModel();
                                try {
                                        MappingModelToApi.mapTModel(modelTModel, apitmodel);
                                } catch (DispositionReportFaultMessage ex) {
                                        log.warn(ex);
                                        apitmodel=null;
                                }


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

        }
        return apitmodel;
}
 
源代码13 项目: james-project   文件: JPATransactionalMapper.java
@Override
protected void rollback() throws MailboxException {
    EntityTransaction transaction = entityManager.getTransaction();
    // check if we have a transaction to rollback
    if (transaction.isActive()) {
        getEntityManager().getTransaction().rollback();
    }
}
 
源代码14 项目: soapbox-race   文件: SoapboxDao.java
private void remove(ISoapBoxEntity entity) {
	EntityTransaction tx = null;
	try {
		EntityManager manager = ConnectionDB.getManager();
		tx = manager.getTransaction();
		tx.begin();
		manager.remove(entity);
		tx.commit();
	} catch (Exception e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
			e.printStackTrace();
		}
	}
}
 
源代码15 项目: juddi   文件: UDDIReplicationImpl.java
private synchronized UDDIReplicationPortType getReplicationClient(String node) {
        if (cache.containsKey(node)) {
                return cache.get(node);
        }
        UDDIService svc = new UDDIService();
        UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort();
        TransportSecurityHelper.applyTransportSecurity((BindingProvider) replicationClient);

        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
                tx.begin();
                StringBuilder sql = new StringBuilder();
                sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc");
                //sql.toString();
                Query qry = em.createQuery(sql.toString());
                qry.setMaxResults(1);

                org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult();
                for (Operator o : resultList.getOperator()) {
                        if (o.getOperatorNodeID().equalsIgnoreCase(node)) {
                                ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL());
                                cache.put(node, replicationClient);
                                return replicationClient;
                        }
                }
                tx.rollback();

        } catch (Exception ex) {
                logger.fatal("Node not found!" + node, ex);
        } finally {
                if (tx.isActive()) {
                        tx.rollback();
                }
                em.close();
        }
        //em.close();
        return null;

}
 
源代码16 项目: ranger   文件: DbAuditProvider.java
private boolean beginTransaction() {
	EntityTransaction trx = getTransaction();
	
	if(trx != null && !trx.isActive()) {
		trx.begin();
	}

	if(trx == null) {
		LOG.warn("DbAuditProvider.beginTransaction(): trx is null");
	}
	
	return trx != null;
}
 
源代码17 项目: soapbox-race   文件: SoapboxDao.java
private void persist(ISoapBoxEntity entity) {
	EntityTransaction tx = null;
	try {
		EntityManager manager = ConnectionDB.getManager();
		tx = manager.getTransaction();
		tx.begin();
		manager.persist(entity);
		tx.commit();
	} catch (Exception e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
			e.printStackTrace();
		}
	}
}
 
源代码18 项目: Knowage-Server   文件: JPAPersistenceManager.java
@Override
public void updateRecord(JSONObject aRecord, RegistryConfiguration registryConf) {

	EntityTransaction entityTransaction = null;

	logger.debug("IN");
	EntityManager entityManager = null;
	try {
		Assert.assertNotNull(aRecord, "Input parameter [record] cannot be null");
		Assert.assertNotNull(aRecord, "Input parameter [registryConf] cannot be null");

		logger.debug("New record: " + aRecord.toString(3));
		logger.debug("Target entity: " + registryConf.getEntity());

		entityManager = dataSource.getEntityManager();
		Assert.assertNotNull(entityManager, "entityManager cannot be null");

		entityTransaction = entityManager.getTransaction();

		EntityType targetEntity = getTargetEntity(registryConf, entityManager);
		String keyAttributeName = getKeyAttributeName(targetEntity);
		logger.debug("Key attribute name is equal to " + keyAttributeName);

		Iterator it = aRecord.keys();

		Object keyColumnValue = aRecord.get(keyAttributeName);
		logger.debug("Key of new record is equal to " + keyColumnValue);
		logger.debug("Key column java type equal to [" + targetEntity.getJavaType() + "]");
		Attribute a = targetEntity.getAttribute(keyAttributeName);
		Object obj = entityManager.find(targetEntity.getJavaType(), this.convertValue(keyColumnValue, a));
		logger.debug("Key column class is equal to [" + obj.getClass().getName() + "]");

		while (it.hasNext()) {
			String attributeName = (String) it.next();
			logger.debug("Processing column [" + attributeName + "] ...");

			if (keyAttributeName.equals(attributeName)) {
				logger.debug("Skip column [" + attributeName + "] because it is the key of the table");
				continue;
			}
			Column column = registryConf.getColumnConfiguration(attributeName);
			if (!column.isEditable()) {
				logger.debug("Skip column [" + attributeName + "] because it is not editable");
				continue;
			}
			List columnDepends = new ArrayList();
			if (column.getDependences() != null && !"".equals(column.getDependences())) {
				String[] dependences = column.getDependences().split(",");
				for (int i = 0; i < dependences.length; i++) {
					// get dependences informations
					Column dependenceColumns = getDependenceColumns(registryConf.getColumns(), dependences[i]);
					if (dependenceColumns != null)
						columnDepends.add(dependenceColumns);
				}
			}

			// if column is info column do not update
			if (!column.isInfoColumn()) {
				if (column.getSubEntity() != null) {
					logger.debug("Column [" + attributeName + "] is a foreign key");
					manageForeignKey(targetEntity, column, obj, attributeName, aRecord, columnDepends, entityManager, registryConf.getColumns());
				} else {
					logger.debug("Column [" + attributeName + "] is a normal column");
					manageProperty(targetEntity, obj, attributeName, aRecord);
				}
			}
		}

		if (!entityTransaction.isActive()) {
			entityTransaction.begin();
		}

		entityManager.persist(obj);
		entityManager.flush();
		entityTransaction.commit();

	} catch (Throwable t) {
		if (entityTransaction != null && entityTransaction.isActive()) {
			entityTransaction.rollback();
		}
		logger.error(t);
		throw new SpagoBIRuntimeException("Error saving entity", t);
	} finally {
		if (entityManager != null) {
			if (entityManager.isOpen()) {
				entityManager.close();
			}
		}
		logger.debug("OUT");
	}

}
 
源代码19 项目: james-project   文件: JPADomainList.java
private void rollback(EntityTransaction transaction) {
    if (transaction.isActive()) {
        transaction.rollback();
    }
}
 
源代码20 项目: mycore   文件: MCRURNGranularRESTService.java
private MCRDNBURN registerURN(MCRDerivate deriv, String filePath) throws MCRPersistentIdentifierException {
    MCRObjectID derivID = deriv.getId();

    Function<String, Integer> countCreatedPI = s -> MCRPIManager
        .getInstance()
        .getCreatedIdentifiers(derivID, getType(), getServiceID())
        .size();

    int seed = Optional.of(filePath)
        .filter(p -> !"".equals(p))
        .map(countCreatedPI)
        .map(count -> count + 1)
        .orElse(1);

    MCRDNBURN derivURN = Optional
        .ofNullable(deriv.getDerivate())
        .map(MCRObjectDerivate::getURN)
        .flatMap(new MCRDNBURNParser()::parse)
        .orElseGet(() -> createNewURN(deriv));

    String setID = derivID.getNumberAsString();
    GranularURNGenerator granularURNGen = new GranularURNGenerator(seed, derivURN, setID);
    Function<MCRPath, Supplier<String>> generateURN = p -> granularURNGen.getURNSupplier();

    LinkedHashMap<Supplier<String>, MCRPath> urnPathMap = derivateFileStream.apply(deriv)
        .filter(notInIgnoreList().and(matchFile(filePath)))
        .sorted()
        .collect(Collectors.toMap(generateURN, p -> p, (m1, m2) -> m1,
            LinkedHashMap::new));

    if (!"".equals(filePath) && urnPathMap.isEmpty()) {
        String errMsg = new MessageFormat("File {0} does not exist in {1}.\n", Locale.ROOT)
            .format(new Object[] { filePath, derivID.toString() })
            + "Use absolute path of file without owner ID like /abs/path/to/file.\n";

        throw new MCRPersistentIdentifierException(errMsg);
    }

    urnPathMap.forEach(createFileMetadata(deriv).andThen(persistURN(deriv)));

    try {
        MCRMetadataManager.update(deriv);
    } catch (MCRPersistenceException | MCRAccessException e) {
        LOGGER.error("Error while updating derivate {}", derivID, e);
    }

    EntityTransaction transaction = MCREntityManagerProvider
        .getCurrentEntityManager()
        .getTransaction();

    if (!transaction.isActive()) {
        transaction.begin();
    }

    transaction.commit();

    return derivURN;
}