Java Code Examples for javax.persistence.EntityManager#getTransaction()

The following examples show how to use javax.persistence.EntityManager#getTransaction() . 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: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: PersistenceUtils.java    From kumuluzee with MIT License 6 votes vote down vote up
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;
        }
    }
 
Example 3
Source File: JPAUtil.java    From juddi with Apache License 2.0 6 votes vote down vote up
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();
	}
}
 
Example 4
Source File: TransactionExecutor.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
        });
    }
 
Example 5
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 6
Source File: LdapSimpleAuthenticator.java    From juddi with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 7
Source File: JpaTest.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 查询策略:使用延迟加载策略
 *  只有使用对象时才会执行查询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();
    }
}
 
Example 8
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 9
Source File: JPAUsersDAO.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 10
Source File: BaseDao.java    From ranger with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 11
Source File: JPAUtil.java    From juddi with Apache License 2.0 6 votes vote down vote up
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();
	}
	
}
 
Example 12
Source File: DatabasesTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: JPALink.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
public void save() {
  EntityManager em = context.getEntityManager();
  EntityTransaction tx = em.getTransaction();

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

}
 
Example 15
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void verifyListOfExistingPersons(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    listExistingPersons(em);
    transaction.commit();
    em.close();
}
 
Example 16
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 17
Source File: JPADAO.java    From rome with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 18
Source File: BasicModelTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example 19
Source File: JPAPersistenceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@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");
	}

}
 
Example 20
Source File: UDDISubscriptionListenerImpl.java    From juddi with Apache License 2.0 4 votes vote down vote up
@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;
}