Search in sources :

Example 1 with Product

use of com.vladmihalcea.hibernate.model.store.Product in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateEqualsHashCodeTest method testChildObjects.

@Test
public void testChildObjects() {
    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();
        }
    });
    Product product = transactionTemplate.execute(new TransactionCallback<Product>() {

        @Override
        public Product doInTransaction(TransactionStatus transactionStatus) {
            return entityManager.createQuery("select p " + "from Product p " + "left join fetch p.images i " + "where p.id = :productId", Product.class).setParameter("productId", productId).getSingleResult();
        }
    });
    Image frontImage = new Image();
    frontImage.setName("front image");
    frontImage.setProduct(product);
    frontImage.setIndex(0);
    assertTrue(product.getImages().contains(frontImage));
    List<Image> images = transactionTemplate.execute(new TransactionCallback<List<Image>>() {

        @Override
        public List<Image> doInTransaction(TransactionStatus transactionStatus) {
            return entityManager.createQuery("select i from Image i ", Image.class).getResultList();
        }
    });
    try {
        assertTrue(new HashSet<Image>(images).contains(frontImage));
        fail("Should have thrown LazyInitializationException!");
    } catch (LazyInitializationException expected) {
    }
}
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) LazyInitializationException(org.hibernate.LazyInitializationException) List(java.util.List) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 2 with Product

use of com.vladmihalcea.hibernate.model.store.Product in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateJTATransactionIsolationTest method test.

@Test
public void test() {
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);
            Product product1 = new Product("tvCode");
            product1.setName("TV");
            product1.setCompany(company);
            Image frontImage1 = new Image();
            frontImage1.setName("front image 1");
            frontImage1.setIndex(0);
            Image sideImage1 = new Image();
            sideImage1.setName("side image 1");
            sideImage1.setIndex(1);
            product1.addImage(frontImage1);
            product1.addImage(sideImage1);
            WarehouseProductInfo warehouseProductInfo1 = new WarehouseProductInfo();
            warehouseProductInfo1.setQuantity(101);
            product1.addWarehouse(warehouseProductInfo1);
            entityManager.persist(product1);
            Product product = entityManager.find(Product.class, 1L);
            product.setQuantity(10);
            return null;
        }
    });
    storeService.purchase(1L);
}
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) Test(org.junit.Test)

Example 3 with Product

use of com.vladmihalcea.hibernate.model.store.Product 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 4 with Product

use of com.vladmihalcea.hibernate.model.store.Product in project vladmihalcea.wordpress.com by vladmihalcea.

the class OptimisticLockingTest method testRetries.

@Test
public void testRetries() throws InterruptedException {
    final Product product = productService.newProduct();
    assertEquals(0, product.getVersion());
    Product savedProduct = productService.updateName(product.getId(), "name");
    assertEquals(1, savedProduct.getVersion());
    final int threadsNumber = 10;
    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);
    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(product.getId(), UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Product(com.vladmihalcea.hibernate.model.store.Product) CountDownLatch(java.util.concurrent.CountDownLatch) OptimisticLockException(javax.persistence.OptimisticLockException) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) Test(org.junit.Test)

Example 5 with Product

use of com.vladmihalcea.hibernate.model.store.Product in project vladmihalcea.wordpress.com by vladmihalcea.

the class StoreServiceImpl method purchase.

@Override
@Transactional(isolation = Isolation.SERIALIZABLE)
public void purchase(Long productId) {
    Product product = entityManager.find(Product.class, 1L);
    Session session = (Session) entityManager.getDelegate();
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation()));
        }
    });
    product.setQuantity(product.getQuantity() - 1);
}
Also used : SQLException(java.sql.SQLException) Work(org.hibernate.jdbc.Work) Connection(java.sql.Connection) Product(com.vladmihalcea.hibernate.model.store.Product) Session(org.hibernate.Session) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

Product (com.vladmihalcea.hibernate.model.store.Product)8 Company (com.vladmihalcea.hibernate.model.store.Company)6 WarehouseProductInfo (com.vladmihalcea.hibernate.model.store.WarehouseProductInfo)6 Test (org.junit.Test)6 TransactionStatus (org.springframework.transaction.TransactionStatus)5 Image (com.vladmihalcea.hibernate.model.store.Image)4 List (java.util.List)2 Transactional (org.springframework.transaction.annotation.Transactional)2 SQLSelectCountMismatchException (com.vladmihalcea.sql.exception.SQLSelectCountMismatchException)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 OptimisticLockException (javax.persistence.OptimisticLockException)1 PersistenceException (javax.persistence.PersistenceException)1 LazyInitializationException (org.hibernate.LazyInitializationException)1 Session (org.hibernate.Session)1 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)1