package org.nutz.trans;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.nutz.dao.test.DaoCase;
import org.nutz.lang.Lang;

public class SimpleTransTest extends DaoCase {

    @Before
    public void before() {
        dao.create(Company.class, true);
        dao.create(Master.class, true);
        dao.create(Cat.class, true);
        dao.insert(Cat.create("xb"));

    }

    @Test
    public void test_update_rollback() {

        final Cat cat = dao.fetch(Cat.class, "xb");
        try {
            Trans.exec(new Atom() {
                public void run() {
                    cat.setName("PPP");
                    dao.update(cat);
                    throw Lang.makeThrow("Quite!!!");
                }
            });
            fail();
        }
        catch (RuntimeException e) {}
        Cat xb = dao.fetch(Cat.class, "xb");
        assertTrue(xb.getId() > 0);
    }

    @Test
    public void test_batch_update_rollback() {
        final Cat cat1 = dao.fetch(Cat.class, "xb");
        final Cat cat2 = new Cat();
        cat2.setId(cat1.getId() + 1);
        cat2.setMaster(cat1.getMaster());
        cat2.setMasterId(cat1.getMasterId());
        cat2.setName("xb2");
        dao.insert(cat2);
        assertTrue(dao.fetch(Cat.class, "xb2").getName().equals("xb2"));
        try {
            Trans.exec(new Atom() {
                public void run() {
                    cat1.setName("p1");
                    dao.update(cat1);
                    cat2.setName("p2");
                    dao.update(cat2);
                    throw Lang.makeThrow("Quite!!!");
                }
            });
            fail();
        }
        catch (RuntimeException e) {}
        assertTrue(dao.fetch(Cat.class, "xb").getName().equals("xb"));
        assertTrue(dao.fetch(Cat.class, "xb2").getName().equals("xb2"));
        dao.delete(cat2);
    }

}

@@ -53,24 +53,55 @@
 ssert.*;%0D%0A%0D%0A
+import java.sql.Connection;%0D%0A%0D%0A
 import org.j
@@ -138,16 +138,51 @@
 .Test;%0D%0A
+import org.nutz.dao.ConnCallback;%0D%0A
 import o
@@ -2033,11 +2033,692 @@
    %7D%0D%0A%0D%0A
+%0D%0A    @Test%0D%0A    public void test_issue312() %7B%0D%0A        Trans.exec(new Atom()%7B%0D%0A            public void run() %7B%0D%0A                final Connection%5B%5D conns = new Connection%5B2%5D;%0D%0A                dao.run(new ConnCallback() %7B%0D%0A                    public void invoke(Connection conn) throws Exception %7B%0D%0A                        conns%5B0%5D = conn;%0D%0A                    %7D %0D%0A                %7D);%0D%0A                dao.run(new ConnCallback() %7B%0D%0A                    public void invoke(Connection conn) throws Exception %7B%0D%0A                        conns%5B1%5D = conn;%0D%0A                    %7D %0D%0A                %7D);%0D%0A                assertEquals(conns%5B0%5D, conns%5B1%5D);%0D%0A            %7D %0D%0A        %7D);%0D%0A    %7D%0D%0A
 %7D%0D%0A

add testcase for issue #312