javax.persistence.EntityManager#getTransaction ( )源码实例Demo

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

源代码1 项目: quarkus   文件: JPAFunctionalityTestEndpoint.java
private static void verifyJPANamedQuery(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    TypedQuery<Person> typedQuery = em.createNamedQuery(
            "get_person_by_name", Person.class);
    typedQuery.setParameter("name", "Quarkus");
    final Person singleResult = typedQuery.getSingleResult();

    if (!singleResult.getName().equals("Quarkus")) {
        throw new RuntimeException("Wrong result from named JPA query");
    }

    transaction.commit();
    em.close();
}
 
源代码2 项目: juddi   文件: JPAUtil.java
public static List<?> runQuery(String qry, int maxRows, int listHead) {
	EntityManager em = PersistenceManager.getEntityManager();
	EntityTransaction tx = em.getTransaction();
	try {
		tx.begin();
		Query q = em.createQuery(qry);
		q.setMaxResults(maxRows);
		q.setFirstResult(listHead);
		List<?> ret =  q.getResultList();
		tx.commit();
		return ret;
	} finally {
		if (tx.isActive()) {
			tx.rollback();
		}
		em.close();
	}
	
}
 
源代码3 项目: ranger   文件: BaseDao.java
public boolean beginTransaction() {
	boolean ret = false;

	EntityManager em = getEntityManager();

	if(em != null) {
		EntityTransaction et = em.getTransaction();
		
		// check the transaction is not already active
		if(et != null && !et.isActive()) {
			et.begin();
			ret = true;
		}
	}
	
	return ret;
}
 
源代码4 项目: james-project   文件: JPAUsersDAO.java
@Override
public void addUser(Username username, String password) throws UsersRepositoryException {
    Username lowerCasedUsername = Username.of(username.asString().toLowerCase(Locale.US));
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername.asString() + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername.asString(), password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        LOGGER.debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username.asString(), e);
    } finally {
        EntityManagerUtils.safelyClose(entityManager);
    }
}
 
private static void storeTestPokemonTrainers(final EntityManagerFactory emf, Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Pokemon rocky = new Pokemon(68, "Rocky", 3056);
    final Pokemon sonGoku = new Pokemon(149, "Son Goku", 3792);
    final Pokemon mmMan = new Pokemon(94, "Marshmallow Man", 2842);
    em.persist(rocky);
    em.persist(sonGoku);
    em.persist(mmMan);
    em.persist(new Trainer(rocky, sonGoku, mmMan));

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
源代码6 项目: code   文件: JpaTest.java
/**
 * 查询策略:使用延迟加载策略
 *  只有使用对象时才会执行查询sql语句:先输出true,再打印sql
 */
@Test
public void testLoadOne() {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        // 1、获取EntityManager
        em = JpaUtil.getEntityManager();
        // 2、获取事务
        tx = em.getTransaction();
        // 3、开启事务
        tx.begin();
        // 4、获取数据
        // primaryKey类型必须和实体主键类型一致,否则查询不到
        Customer c1 = em.getReference(Customer.class, 2L);
        Customer c2 = em.getReference(Customer.class, 2L);
        System.out.println(c1 == c2);
        // 5、提交事务
        tx.commit();
        //System.out.println(c1);
    } catch (Exception e) {
        if (tx != null) tx.rollback();
    } finally {
        if (em != null) em.close();
    }
}
 
源代码7 项目: 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();
    }
}
 
private static void testDeleteViaQuery(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.createNativeQuery("Delete from Person").executeUpdate();
    transaction.commit();
    em.close();

    Statistics stats = getStatistics(emf);

    em = emf.createEntityManager();
    transaction = em.getTransaction();
    transaction.begin();
    if (em.find(Person.class, 1L) != null
            || em.find(Person.class, 2L) != null
            || em.find(Person.class, 3L) != null
            || em.find(Person.class, 4L) != null) {
        throw new RuntimeException("Persons should have been deleted");
    }

    transaction.commit();
    em.close();

    assertRegionStats(new Counts(0, 0, 4, 0), Person.class.getName(), stats);
}
 
private Thread createThread(Consumer<EntityManager> command) {

        return new Thread(() ->{
            EntityManager em = factory.createEntityManager();
            EntityTransaction tx = em.getTransaction();

            tx.begin();
            try{
                command.accept(em);
                tx.commit();
            } catch (Exception e){
                tx.rollback();
                System.out.println("\n\nFailed transaction on separated thread: "+e.getCause().toString()+"\n\n");
            }
            em.close();
        });
    }
 
源代码10 项目: juddi   文件: JPAUtil.java
public static void runUpdateQuery(String qry) {
	EntityManager em = PersistenceManager.getEntityManager();
	EntityTransaction tx = em.getTransaction();
	try {
		tx.begin();
		
		Query q = em.createQuery(qry);
		q.executeUpdate();

		tx.commit();
	} finally {
		if (tx.isActive()) {
			tx.rollback();
		}
		em.close();
	}
}
 
源代码11 项目: kumuluzee   文件: PersistenceUtils.java
public static TransactionType getEntityManagerFactoryTransactionType(EntityManagerFactory emf) {

        EntityManager manager = emf.createEntityManager();

        // Hibernate does not throw exception when getTransaction() in JTA context is called, this is the workaround
        // for JTA detection
        if (emf.getProperties().containsKey("hibernate.transaction.coordinator_class") &&
                emf.getProperties().get("hibernate.transaction.coordinator_class") instanceof Class &&
                ((Class) emf.getProperties().get("hibernate.transaction.coordinator_class")).getSimpleName()
                        .equals("JtaTransactionCoordinatorBuilderImpl")) {
            return TransactionType.JTA;
        }

        try {
            manager.getTransaction();

            return TransactionType.RESOURCE_LOCAL;
        } catch (IllegalStateException e) {

            manager.close();
            return TransactionType.JTA;
        }
    }
 
源代码12 项目: quarkus   文件: JPAFunctionalityTestEndpoint.java
private static void verifyListOfExistingPersons(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    listExistingPersons(em);
    transaction.commit();
    em.close();
}
 
源代码13 项目: cloud-odata-java   文件: JPALink.java
public void save() {
  EntityManager em = context.getEntityManager();
  EntityTransaction tx = em.getTransaction();

  if (!tx.isActive()) {
    em.getTransaction().begin();
    em.persist(sourceJPAEntity);
    em.getTransaction().commit();
  }

}
 
源代码14 项目: joynr   文件: DatabasesTest.java
@Test
@Ignore
public void testCascadingDelete() {

    Assert.assertEquals(0, channelDb.getChannels().size());

    ControlledBounceProxyInformation bpInfo = new ControlledBounceProxyInformation("bp1.0",
                                                                                   URI.create("http://www.joynr1.de/bp1/"));
    Mockito.when(mockTimestampProvider.getCurrentTime()).thenReturn(1000l);
    bounceProxyDb.addBounceProxy(bpInfo);
    channelDb.addChannel(new Channel(bpInfo, "channel1", URI.create("http://www.joyn1.de/bp1/channels/channel1")));

    Assert.assertEquals(1, bounceProxyDb.getAssignableBounceProxies().size());
    Assert.assertEquals(1, channelDb.getChannels().size());

    // delete bounce proxy
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();

    Query deleteBounceProxiesQuery = em.createQuery("DELETE FROM BounceProxyEntity");
    Assert.assertEquals(3, deleteBounceProxiesQuery.executeUpdate());

    tx.commit();

    Assert.assertEquals(0, bounceProxyDb.getAssignableBounceProxies().size());
    Assert.assertEquals(0, channelDb.getChannels().size());

    tx.begin();

    Query deleteBounceProxyInformationQuery = em.createQuery("DELETE FROM BounceProxyInformationEntity");
    Assert.assertEquals(0, deleteBounceProxyInformationQuery.executeUpdate());

    Query deleteChannelsQuery = em.createQuery("DELETE FROM ChannelEntity");
    Assert.assertEquals(0, deleteChannelsQuery.executeUpdate());

    tx.commit();
}
 
源代码15 项目: quarkus   文件: JPAFunctionalityTestEndpoint.java
private static void deleteAllPerson(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.createNativeQuery("Delete from Person").executeUpdate();
    transaction.commit();
    em.close();
}
 
private static void deleteAll(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.createNativeQuery("Delete from Person").executeUpdate();
    em.createNativeQuery("Delete from Item").executeUpdate();
    em.createNativeQuery("Delete from Citizen").executeUpdate();
    em.createNativeQuery("Delete from Country").executeUpdate();
    em.createNativeQuery("Delete from Pokemon").executeUpdate();
    em.createNativeQuery("Delete from Trainer").executeUpdate();
    transaction.commit();
    em.close();
}
 
源代码17 项目: juddi   文件: UDDISubscriptionListenerImpl.java
@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(
		NotifySubscriptionListener body)
		throws DispositionReportFaultMessage {
	try {
		JAXBContext context = JAXBContext.newInstance(body.getClass());
		Marshaller marshaller = context.createMarshaller();
		StringWriter sw = new StringWriter();
		marshaller.marshal(body, sw);

		logger.info("Notification received by UDDISubscriptionListenerService : " + sw.toString());
		
		@SuppressWarnings("rawtypes")
		NotificationList nl = NotificationList.getInstance();
		nl.getNotifications().add(sw.toString());
		
		org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null;
		
		//find the clerks to go with this subscription
		EntityManager em = PersistenceManager.getEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
	
			this.getEntityPublisher(em, body.getAuthInfo());
			String subscriptionKey = body.getSubscriptionResultsList().getSubscription().getSubscriptionKey();
			org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
			try {
				modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey);
			} catch (ClassCastException e) {}
			if (modelClientSubscriptionInfo == null) {
				throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
			}
			apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
			MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo,em);
	
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			em.close();
		}
		
		XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(),apiClientSubscriptionInfo.getToClerk(), body.getSubscriptionResultsList());
		
	} catch (JAXBException jaxbe) {
		logger.error("", jaxbe);
		throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client"));
	}	
	
	new ValidateSubscriptionListener().validateNotification(body);
		
	DispositionReport dr = new DispositionReport();
	Result res = new Result();
	dr.getResult().add(res);
	return dr;
}
 
源代码18 项目: pnc   文件: BasicModelTest.java
@Test
public void testProductMilestoneAndRelease() throws Exception {

    EntityManager em = getEmFactory().createEntityManager();
    ProductMilestone productMilestone1 = em.find(ProductMilestone.class, 1);

    TargetRepository targetRepository = getTargetRepository("builds-untested3");

    Artifact artifact = Artifact.Builder.newBuilder()
            .identifier("org.test:artifact1:1.0:jar")
            .md5("md-fake-987654321")
            .sha1("sha1-fake-987654321")
            .sha256("sha256-fake-987654321")
            .filename("artifact1.jar")
            .originUrl("http://central.maven.org/maven2/test.jar")
            .importDate(Date.from(Instant.now()))
            .targetRepository(targetRepository)
            .build();
    productMilestone1.addDistributedArtifact(artifact);
    ProductRelease productRelease1 = ProductRelease.Builder.newBuilder()
            .version("1.0.0.Beta1")
            .productMilestone(productMilestone1)
            .build();

    productRelease1.setProductMilestone(productMilestone1);

    EntityTransaction tx = em.getTransaction();

    try {
        tx.begin();
        em.persist(targetRepository);
        em.persist(artifact);
        em.persist(productMilestone1);
        em.persist(productRelease1);
        tx.commit();

        ProductRelease release = em.find(ProductRelease.class, productRelease1.getId());
        Assert.assertEquals(1, release.getProductMilestone().getDistributedArtifacts().size());
    } catch (RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        em.close();
    }
}
 
源代码19 项目: rome   文件: JPADAO.java
@Override
public List<? extends Subscriber> subscribersForTopic(final String topic) {
    final LinkedList<JPASubscriber> result = new LinkedList<JPASubscriber>();
    final EntityManager em = factory.createEntityManager();
    final EntityTransaction tx = em.getTransaction();
    tx.begin();

    final Query query = em.createNamedQuery("Subcriber.forTopic");
    query.setParameter("topic", topic);

    try {
        @SuppressWarnings("unchecked")
        final List<JPASubscriber> subscribers = query.getResultList();
        for (final JPASubscriber subscriber : subscribers) {
            if (subscriber.getLeaseSeconds() == -1) {
                result.add(subscriber);
                continue;
            }

            if (subscriber.getSubscribedAt().getTime() < System.currentTimeMillis() - 1000 * subscriber.getLeaseSeconds()) {
                subscriber.setExpired(true);
            } else {
                result.add(subscriber);
            }

            if (subscriber.isExpired() && purgeExpired) {
                em.remove(subscriber);
            }
        }
    } catch (final NoResultException e) {
        tx.rollback();
        em.close();

        return result;
    }

    if (!tx.getRollbackOnly()) {
        tx.commit();
    } else {
        tx.rollback();
    }

    em.close();

    return result;
}
 
源代码20 项目: Knowage-Server   文件: JPAPersistenceManager.java
@Override
public void deleteRecord(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("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 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() + "]");

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

		// String q =
		// "DELETE from "+targetEntity.getName()+" o WHERE o."+keyAttributeName+"="+keyColumnValue.toString();
		String q = "DELETE from " + targetEntity.getName() + " WHERE " + keyAttributeName + "=" + keyColumnValue.toString();
		logger.debug("create Query " + q);
		Query deleteQuery = entityManager.createQuery(q);

		int deleted = deleteQuery.executeUpdate();

		// entityManager.remove(obj);
		// entityManager.flush();
		entityTransaction.commit();

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

}