package com.vladmihalcea.hibernate.masterclass.laboratory.concurrency;

import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.dialect.lock.OptimisticEntityLockException;
import org.junit.Test;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.concurrent.Callable;

import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;

/**
 * LockModeOptimisticTest - Test to check LockMode.OPTIMISTIC
 *
 * @author Vlad Mihalcea
 */
public class LockModeOptimisticTest extends AbstractTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Product.class,
            OrderLine.class
        };
    }

    @Test
    public void testImplicitOptimisticLockingN() {

        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {
                Product product = new Product();
                product.setId(1L);
                product.setPrice(BigDecimal.valueOf(12, 99));
                session.persist(product);

                return null;
            }
        });

        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {
                final Product product = (Product) session.get(Product.class, 1L);
                try {
                    executeAndWait(new Callable<Void>() {
                        @Override
                        public Void call() throws Exception {
                            return doInTransaction(new TransactionCallable<Void>() {
                                @Override
                                public Void execute(Session _session) {
                                    Product otherThreadProduct = (Product) _session.get(Product.class, 1L);
                                    assertNotSame(product, otherThreadProduct);
                                    otherThreadProduct.setPrice(BigDecimal.valueOf(14.49));
                                    return null;
                                }
                            });
                        }
                    });
                } catch (Exception e) {
                    fail(e.getMessage());
                }
                OrderLine orderLine = new OrderLine();
                orderLine.setProduct(product);
                session.persist(orderLine);
                return null;
            }
        });
    }

    @Test
    public void testExplicitOptimisticLockingN() {

        doInTransaction(new TransactionCallable<Void>() {
            @Override
            public Void execute(Session session) {
                Product product = new Product();
                product.setId(1L);
                product.setPrice(BigDecimal.valueOf(12, 99));
                session.persist(product);

                return null;
            }
        });

        try {
            doInTransaction(new TransactionCallable<Void>() {
                @Override
                public Void execute(Session session) {
                    final Product product = (Product) session.get(Product.class, 1L, new LockOptions(LockMode.OPTIMISTIC));

                    executeAndWait(new Callable<Void>() {
                        @Override
                        public Void call() throws Exception {
                            return doInTransaction(new TransactionCallable<Void>() {
                                @Override
                                public Void execute(Session _session) {
                                    Product otherThreadProduct = (Product) _session.get(Product.class, 1L);
                                    assertNotSame(product, otherThreadProduct);
                                    otherThreadProduct.setPrice(BigDecimal.valueOf(14.49));
                                    return null;
                                }
                            });
                        }
                    });

                    OrderLine orderLine = new OrderLine();
                    orderLine.setProduct(product);
                    session.persist(orderLine);
                    return null;
                }
            });
            fail("It should have thrown OptimisticEntityLockException!");
        } catch (OptimisticEntityLockException expected) {
            LOGGER.info("Failure: ", expected);
        }
    }

    /**
     * Product - Product
     *
     * @author Vlad Mihalcea
     */
    @Entity(name = "product")
    @Table(name = "product")
    public static class Product {

        @Id
        private Long id;

        private BigDecimal price;

        @Version
        private int version;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public BigDecimal getPrice() {
            return price;
        }

        public void setPrice(BigDecimal price) {
            this.price = price;
        }
    }

    /**
     * OrderLine - Order Line
     *
     * @author Vlad Mihalcea
     */
    @Entity(name = "OrderLine")
    @Table(name = "order_line")
    public static class OrderLine {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        @ManyToOne
        private Product product;

        @Version
        private int version;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }
    }
}

@@ -297,24 +297,49 @@
 kException;%0A
+import org.junit.Before;%0A
 import org.j
@@ -349,16 +349,16 @@
 t.Test;%0A
-
 %0Aimport 
@@ -842,36 +842,38 @@
  %7D;%0A    %7D%0A%0A    @
-Test
+Before
 %0A    public void
@@ -877,43 +877,38 @@
 oid 
-testImplicitOptimisticLockingN() %7B%0A
+init() %7B%0A        super.init();
 %0A   
@@ -1111,32 +1111,91 @@
 duct.setId(1L);%0A
+                product.setDescription(%22USB Flash Drive%22);%0A
                 
@@ -1274,33 +1274,32 @@
 rsist(product);%0A
-%0A
                 
@@ -1328,32 +1328,100 @@
    %7D%0A        %7D);
+%0A    %7D%0A%0A    @Test%0A    public void testImplicitOptimisticLockingN() %7B
 %0A%0A        doInTr
@@ -2813,384 +2813,8 @@
  %7B%0A%0A
-        doInTransaction(new TransactionCallable%3CVoid%3E() %7B%0A            @Override%0A            public Void execute(Session session) %7B%0A                Product product = new Product();%0A                product.setId(1L);%0A                product.setPrice(BigDecimal.valueOf(12, 99));%0A                session.persist(product);%0A%0A                return null;%0A            %7D%0A        %7D);%0A%0A
     
@@ -4514,32 +4514,69 @@
 ivate Long id;%0A%0A
+        private String description;%0A%0A
         private 
@@ -4734,32 +4734,32 @@
 etId(Long id) %7B%0A
-
             this
@@ -4771,32 +4771,228 @@
  id;%0A        %7D%0A%0A
+        public String getDescription() %7B%0A            return description;%0A        %7D%0A%0A        public void setDescription(String description) %7B%0A            this.description = description;%0A        %7D%0A%0A
         public B

Refactor tests for optimistic locking