Search in sources :

Example 61 with PersistenceException

use of javax.persistence.PersistenceException in project aries by apache.

the class TxContextBindingEntityManager method getRealEntityManager.

@Override
protected final EntityManager getRealEntityManager() {
    TransactionContext txContext = txControl.getCurrentContext();
    if (txContext == null) {
        throw new TransactionException("The resource " + provider + " cannot be accessed outside of an active Transaction Context");
    }
    EntityManager existing = (EntityManager) txContext.getScopedValue(resourceId);
    if (existing != null) {
        return existing;
    }
    EntityManager toReturn;
    EntityManager toClose;
    try {
        if (txContext.getTransactionStatus() == NO_TRANSACTION) {
            toClose = provider.createEntityManager();
            toReturn = new ScopedEntityManagerWrapper(toClose);
        } else if (txContext.supportsLocal()) {
            toClose = provider.createEntityManager();
            toReturn = new TxEntityManagerWrapper(toClose);
            txContext.registerLocalResource(getLocalResource(toClose));
            toClose.getTransaction().begin();
        } else {
            throw new TransactionException("There is a transaction active, but it does not support local participants");
        }
    } catch (Exception sqle) {
        throw new TransactionException("There was a problem getting hold of a database connection", sqle);
    }
    txContext.postCompletion(x -> {
        try {
            toClose.close();
        } catch (PersistenceException sqle) {
        }
    });
    txContext.putScopedValue(resourceId, toReturn);
    return toReturn;
}
Also used : EntityManager(javax.persistence.EntityManager) ScopedEntityManagerWrapper(org.apache.aries.tx.control.jpa.common.impl.ScopedEntityManagerWrapper) TransactionException(org.osgi.service.transaction.control.TransactionException) TxEntityManagerWrapper(org.apache.aries.tx.control.jpa.common.impl.TxEntityManagerWrapper) TransactionContext(org.osgi.service.transaction.control.TransactionContext) PersistenceException(javax.persistence.PersistenceException) PersistenceException(javax.persistence.PersistenceException) TransactionException(org.osgi.service.transaction.control.TransactionException)

Example 62 with PersistenceException

use of javax.persistence.PersistenceException in project deltaspike by apache.

the class QueryStringExtractorFactoryTest method should_unwrap_query_even_proxied.

@Test
public void should_unwrap_query_even_proxied() {
    // when
    String extracted = factory.extract((Query) newProxyInstance(currentThread().getContextClassLoader(), new Class[] { Query.class }, new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("toString")) {
                return "Unknown provider wrapper for tests.";
            }
            if (method.getName().equals("unwrap")) {
                Class<?> clazz = (Class<?>) args[0];
                if (clazz.getName().contains("hibernate") || clazz.getName().contains("openjpa") || clazz.getName().contains("eclipse")) {
                    return createProxy(clazz);
                } else {
                    throw new PersistenceException("Unable to unwrap for " + clazz);
                }
            }
            return null;
        }
    }));
    // then
    assertEquals(QUERY_STRING, extracted);
}
Also used : PersistenceException(javax.persistence.PersistenceException) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) Test(org.junit.Test)

Example 63 with PersistenceException

use of javax.persistence.PersistenceException in project logging-log4j2 by apache.

the class ContextDataJsonAttributeConverter method convertToEntityAttribute.

@Override
public ReadOnlyStringMap convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }
    try {
        final StringMap result = ContextDataFactory.createContextData();
        final ObjectNode root = (ObjectNode) OBJECT_MAPPER.readTree(s);
        final Iterator<Map.Entry<String, JsonNode>> entries = root.fields();
        while (entries.hasNext()) {
            final Map.Entry<String, JsonNode> entry = entries.next();
            // Don't know what to do with non-text values.
            // Maybe users who need this need to provide custom converter?
            final Object value = entry.getValue().textValue();
            result.putValue(entry.getKey(), value);
        }
        return result;
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to map.", e);
    }
}
Also used : ReadOnlyStringMap(org.apache.logging.log4j.util.ReadOnlyStringMap) StringMap(org.apache.logging.log4j.util.StringMap) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) PersistenceException(javax.persistence.PersistenceException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ReadOnlyStringMap(org.apache.logging.log4j.util.ReadOnlyStringMap) Map(java.util.Map) StringMap(org.apache.logging.log4j.util.StringMap)

Example 64 with PersistenceException

use of javax.persistence.PersistenceException in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateOperationsOrderTest method test.

@Test
public void test() {
    final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() {

        @Override
        public Long doInTransaction(TransactionStatus transactionStatus) {
            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);
            Product product = new Product("tvCode");
            product.setName("TV");
            product.setCompany(company);
            Image frontImage = new Image();
            frontImage.setName("front image");
            frontImage.setIndex(0);
            Image sideImage = new Image();
            sideImage.setName("side image");
            sideImage.setIndex(1);
            product.addImage(frontImage);
            product.addImage(sideImage);
            WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
            warehouseProductInfo.setQuantity(101);
            product.addWarehouse(warehouseProductInfo);
            entityManager.persist(product);
            return product.getId();
        }
    });
    try {
        transactionTemplate.execute(new TransactionCallback<Void>() {

            @Override
            public Void doInTransaction(TransactionStatus transactionStatus) {
                Product product = entityManager.find(Product.class, productId);
                assertEquals(2, product.getImages().size());
                Iterator<Image> imageIterator = product.getImages().iterator();
                Image frontImage = imageIterator.next();
                assertEquals("front image", frontImage.getName());
                assertEquals(0, frontImage.getIndex());
                Image sideImage = imageIterator.next();
                assertEquals("side image", sideImage.getName());
                assertEquals(1, sideImage.getIndex());
                Image backImage = new Image();
                backImage.setName("back image");
                backImage.setIndex(1);
                product.removeImage(sideImage);
                product.addImage(backImage);
                product.setName("tv set");
                entityManager.flush();
                return null;
            }
        });
        fail("Expected ConstraintViolationException");
    } catch (PersistenceException expected) {
        assertEquals(ConstraintViolationException.class, expected.getCause().getClass());
    }
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            Product product = entityManager.find(Product.class, productId);
            assertEquals(2, product.getImages().size());
            Iterator<Image> imageIterator = product.getImages().iterator();
            Image frontImage = imageIterator.next();
            assertEquals("front image", frontImage.getName());
            Image sideImage = imageIterator.next();
            assertEquals("side image", sideImage.getName());
            Image backImage = new Image();
            backImage.setName("back image");
            backImage.setIndex(1);
            //http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29
            product.removeImage(sideImage);
            entityManager.flush();
            product.addImage(backImage);
            product.setName("tv set");
            entityManager.flush();
            return null;
        }
    });
}
Also used : WarehouseProductInfo(com.vladmihalcea.hibernate.model.store.WarehouseProductInfo) Company(com.vladmihalcea.hibernate.model.store.Company) TransactionStatus(org.springframework.transaction.TransactionStatus) Product(com.vladmihalcea.hibernate.model.store.Product) Image(com.vladmihalcea.hibernate.model.store.Image) Iterator(java.util.Iterator) PersistenceException(javax.persistence.PersistenceException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Test(org.junit.Test)

Example 65 with PersistenceException

use of javax.persistence.PersistenceException in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateBagMultiLevelFetchTest method test.

@Test
public void test() {
    final Long forestId = transactionTemplate.execute(new TransactionCallback<Long>() {

        @Override
        public Long doInTransaction(TransactionStatus transactionStatus) {
            BagForest forest = new BagForest();
            BagTree tree1 = new BagTree();
            tree1.setIndex(0);
            BagBranch branch11 = new BagBranch();
            branch11.setIndex(0);
            BagLeaf leaf111 = new BagLeaf();
            leaf111.setIndex(0);
            BagLeaf leaf112 = new BagLeaf();
            leaf111.setIndex(1);
            BagLeaf leaf113 = new BagLeaf();
            leaf111.setIndex(2);
            BagLeaf leaf114 = new BagLeaf();
            leaf111.setIndex(3);
            branch11.addLeaf(leaf111);
            branch11.addLeaf(leaf112);
            branch11.addLeaf(leaf113);
            branch11.addLeaf(leaf114);
            BagBranch branch12 = new BagBranch();
            branch12.setIndex(1);
            BagLeaf leaf121 = new BagLeaf();
            leaf121.setIndex(1);
            BagLeaf leaf122 = new BagLeaf();
            leaf122.setIndex(2);
            BagLeaf leaf123 = new BagLeaf();
            leaf123.setIndex(3);
            BagLeaf leaf124 = new BagLeaf();
            leaf124.setIndex(4);
            branch12.addLeaf(leaf121);
            branch12.addLeaf(leaf122);
            branch12.addLeaf(leaf123);
            branch12.addLeaf(leaf124);
            tree1.addBranch(branch11);
            tree1.addBranch(branch12);
            BagTree tree2 = new BagTree();
            tree2.setIndex(1);
            BagBranch branch21 = new BagBranch();
            branch21.setIndex(0);
            BagLeaf leaf211 = new BagLeaf();
            leaf211.setIndex(0);
            BagLeaf leaf212 = new BagLeaf();
            leaf111.setIndex(1);
            BagLeaf leaf213 = new BagLeaf();
            leaf111.setIndex(2);
            BagLeaf leaf214 = new BagLeaf();
            leaf111.setIndex(3);
            branch21.addLeaf(leaf211);
            branch21.addLeaf(leaf212);
            branch21.addLeaf(leaf213);
            branch21.addLeaf(leaf214);
            BagBranch branch22 = new BagBranch();
            branch22.setIndex(2);
            BagLeaf leaf221 = new BagLeaf();
            leaf121.setIndex(0);
            BagLeaf leaf222 = new BagLeaf();
            leaf121.setIndex(1);
            BagLeaf leaf223 = new BagLeaf();
            leaf121.setIndex(2);
            branch22.addLeaf(leaf221);
            branch22.addLeaf(leaf222);
            branch22.addLeaf(leaf223);
            tree2.addBranch(branch21);
            tree2.addBranch(branch22);
            forest.addTree(tree1);
            forest.addTree(tree2);
            entityManager.persist(forest);
            entityManager.flush();
            return forest.getId();
        }
    });
    BagForest forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

        @Override
        public BagForest doInTransaction(TransactionStatus transactionStatus) {
            return entityManager.find(BagForest.class, forestId);
        }
    });
    try {
        navigateForest(forest);
        fail("Should have thrown LazyInitializationException!");
    } catch (LazyInitializationException expected) {
    }
    forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

        @Override
        public BagForest doInTransaction(TransactionStatus transactionStatus) {
            BagForest forest = entityManager.find(BagForest.class, forestId);
            navigateForest(forest);
            return forest;
        }
    });
    try {
        forest = transactionTemplate.execute(new TransactionCallback<BagForest>() {

            @Override
            public BagForest doInTransaction(TransactionStatus transactionStatus) {
                BagForest forest = entityManager.createQuery("select f " + "from BagForest f " + "join fetch f.trees t " + "join fetch t.branches b " + "join fetch b.leaves l ", BagForest.class).getSingleResult();
                return forest;
            }
        });
        fail("Should have thrown MultipleBagFetchException!");
    } catch (PersistenceException expected) {
        assertEquals(MultipleBagFetchException.class, expected.getCause().getClass());
    }
    List<BagLeaf> leaves = transactionTemplate.execute(new TransactionCallback<List<BagLeaf>>() {

        @Override
        public List<BagLeaf> doInTransaction(TransactionStatus transactionStatus) {
            List<BagLeaf> leaves = entityManager.createQuery("select l " + "from BagLeaf l " + "inner join fetch l.branch b " + "inner join fetch b.tree t " + "inner join fetch t.forest f " + "where f.id = :forestId", BagLeaf.class).setParameter("forestId", forestId).getResultList();
            return leaves;
        }
    });
    forest = reconstructForest(leaves, forestId);
    navigateForest(forest);
    final BagBranch firstBranch = forest.getTrees().get(0).getBranches().get(0);
    firstBranch.getLeaves().clear();
    final BagForest toMergeForest = forest;
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            BagForest savedForest = entityManager.merge(toMergeForest);
            if (!firstBranch.getLeaves().equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) {
                LOG.error("Unsafe reusing the bag, changes haven't propagated!");
            }
            entityManager.flush();
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            BagForest savedForest = entityManager.find(BagForest.class, forestId);
            if (!firstBranch.getLeaves().equals(savedForest.getTrees().get(0).getBranches().get(0).getLeaves())) {
                LOG.error("Unsafe reusing the bag, changes haven't propagated!");
            }
            return null;
        }
    });
}
Also used : BagBranch(com.vladmihalcea.hibernate.model.baglist.BagBranch) TransactionStatus(org.springframework.transaction.TransactionStatus) BagTree(com.vladmihalcea.hibernate.model.baglist.BagTree) TransactionCallback(org.springframework.transaction.support.TransactionCallback) BagLeaf(com.vladmihalcea.hibernate.model.baglist.BagLeaf) LazyInitializationException(org.hibernate.LazyInitializationException) BagForest(com.vladmihalcea.hibernate.model.baglist.BagForest) PersistenceException(javax.persistence.PersistenceException) List(java.util.List) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) Test(org.junit.Test)

Aggregations

PersistenceException (javax.persistence.PersistenceException)125 Test (org.junit.Test)66 Session (org.hibernate.Session)50 Transaction (org.hibernate.Transaction)29 EntityManager (javax.persistence.EntityManager)17 IOException (java.io.IOException)12 StaleObjectStateException (org.hibernate.StaleObjectStateException)10 ArrayList (java.util.ArrayList)9 List (java.util.List)9 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)9 SQLGrammarException (org.hibernate.exception.SQLGrammarException)8 TransactionRequiredException (javax.persistence.TransactionRequiredException)7 MessagesEvent (com.openmeap.event.MessagesEvent)5 EntityNotFoundException (javax.persistence.EntityNotFoundException)5 OptimisticLockException (javax.persistence.OptimisticLockException)5 TestForIssue (org.hibernate.testing.TestForIssue)5 GlobalSettings (com.openmeap.model.dto.GlobalSettings)4 NoResultException (javax.persistence.NoResultException)4 LockOptions (org.hibernate.LockOptions)4 StaleStateException (org.hibernate.StaleStateException)4