Search in sources :

Example 26 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project vladmihalcea.wordpress.com by vladmihalcea.

the class HibernateListMultiLevelFetchTest method test.

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

        @Override
        public Long doInTransaction(TransactionStatus transactionStatus) {
            Forest forest = new Forest();
            Tree tree1 = new Tree();
            tree1.setIndex(0);
            Branch branch11 = new Branch();
            branch11.setIndex(0);
            Leaf leaf111 = new Leaf();
            leaf111.setIndex(0);
            Leaf leaf112 = new Leaf();
            leaf111.setIndex(1);
            Leaf leaf113 = new Leaf();
            leaf111.setIndex(2);
            Leaf leaf114 = new Leaf();
            leaf111.setIndex(3);
            branch11.addLeaf(leaf111);
            branch11.addLeaf(leaf112);
            branch11.addLeaf(leaf113);
            branch11.addLeaf(leaf114);
            Branch branch12 = new Branch();
            branch12.setIndex(1);
            Leaf leaf121 = new Leaf();
            leaf121.setIndex(1);
            Leaf leaf122 = new Leaf();
            leaf122.setIndex(2);
            Leaf leaf123 = new Leaf();
            leaf123.setIndex(3);
            Leaf leaf124 = new Leaf();
            leaf124.setIndex(4);
            branch12.addLeaf(leaf121);
            branch12.addLeaf(leaf122);
            branch12.addLeaf(leaf123);
            branch12.addLeaf(leaf124);
            tree1.addBranch(branch11);
            tree1.addBranch(branch12);
            Tree tree2 = new Tree();
            tree2.setIndex(1);
            Branch branch21 = new Branch();
            branch21.setIndex(0);
            Leaf leaf211 = new Leaf();
            leaf211.setIndex(0);
            Leaf leaf212 = new Leaf();
            leaf111.setIndex(1);
            Leaf leaf213 = new Leaf();
            leaf111.setIndex(2);
            Leaf leaf214 = new Leaf();
            leaf111.setIndex(3);
            branch21.addLeaf(leaf211);
            branch21.addLeaf(leaf212);
            branch21.addLeaf(leaf213);
            branch21.addLeaf(leaf214);
            Branch branch22 = new Branch();
            branch22.setIndex(2);
            Leaf leaf221 = new Leaf();
            leaf121.setIndex(0);
            Leaf leaf222 = new Leaf();
            leaf121.setIndex(1);
            Leaf leaf223 = new Leaf();
            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();
        }
    });
    Forest forest = transactionTemplate.execute(new TransactionCallback<Forest>() {

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

        @Override
        public Forest doInTransaction(TransactionStatus transactionStatus) {
            Forest f = entityManager.createQuery("select f " + "from Forest f " + "join fetch f.trees t " + "join fetch t.branches b " + "join fetch b.leaves l ", Forest.class).getSingleResult();
            return f;
        }
    });
    navigateForest(forest);
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) Branch(com.vladmihalcea.hibernate.model.indexlist.Branch) LazyInitializationException(org.hibernate.LazyInitializationException) TransactionStatus(org.springframework.transaction.TransactionStatus) Forest(com.vladmihalcea.hibernate.model.indexlist.Forest) Tree(com.vladmihalcea.hibernate.model.indexlist.Tree) Leaf(com.vladmihalcea.hibernate.model.indexlist.Leaf) Test(org.junit.Test)

Example 27 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project otter by alibaba.

the class DbDialectTest method test_mysql.

@Test(expectedExceptions = RuntimeException.class)
public void test_mysql() {
    DbDataMedia media = getMysqlMedia();
    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, media.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);
    final SqlTemplate sqlTemplate = dbDialect.getSqlTemplate();
    final JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    final int[] pkColumnTypes = { Types.INTEGER, Types.VARCHAR };
    final int[] columnTypes = { Types.CHAR, Types.DECIMAL, Types.BLOB, Types.CLOB, Types.DATE, Types.TIMESTAMP, Types.TIMESTAMP };
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            int affect = 0;
            String sql = null;
            // 执行insert
            sql = sqlTemplate.getInsertSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps, dbDialect, toTypes(columnTypes, pkColumnTypes), toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }
            });
            want.number(affect).isEqualTo(1);
            // 执行update
            sql = sqlTemplate.getUpdateSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns, true, null);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps, dbDialect, toTypes(columnTypes, pkColumnTypes), toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }
            });
            want.number(affect).isEqualTo(1);
            // 执行deleate
            sql = sqlTemplate.getDeleteSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps, dbDialect, toTypes(pkColumnTypes), toValues(pkColumnValues));
                    return ps.executeUpdate();
                }
            });
            want.number(affect).isEqualTo(1);
            // 执行merge
            sql = sqlTemplate.getMergeSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns, null, true, null);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps, dbDialect, toTypes(columnTypes, pkColumnTypes), toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }
            });
            want.number(affect).isEqualTo(1);
            throw new RuntimeException("rollback");
        }
    });
}
Also used : TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatementCallback(org.springframework.jdbc.core.PreparedStatementCallback) PreparedStatement(java.sql.PreparedStatement) SqlTemplate(com.alibaba.otter.node.etl.common.db.dialect.SqlTemplate) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) TransactionCallback(org.springframework.transaction.support.TransactionCallback) DbDialect(com.alibaba.otter.node.etl.common.db.dialect.DbDialect) DbDataMedia(com.alibaba.otter.shared.common.model.config.data.db.DbDataMedia) Test(org.testng.annotations.Test) BaseDbTest(com.alibaba.otter.node.etl.BaseDbTest)

Example 28 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.

the class PipelineService method save.

public Pipeline save(final Pipeline pipeline) {
    String mutexPipelineName = PipelinePauseService.mutexForPausePipeline(pipeline.getName());
    synchronized (mutexPipelineName) {
        return (Pipeline) transactionTemplate.execute((TransactionCallback) status -> {
            if (pipeline instanceof NullPipeline) {
                return pipeline;
            }
            updateCounter(pipeline);
            Pipeline pipelineWithId = pipelineDao.save(pipeline);
            pipelineLockService.lockIfNeeded(pipelineWithId);
            for (Stage stage : pipeline.getStages()) {
                stageService.save(pipelineWithId, stage);
            }
            pipelineTimeline.update();
            return pipelineWithId;
        });
    }
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString)

Example 29 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.

the class MaterialRepositoryIntegrationTest method shouldRemoveDuplicatesBeforeInsertingModifications.

@Test
public void shouldRemoveDuplicatesBeforeInsertingModifications() {
    final MaterialInstance materialInstance = repo.findOrCreateFrom(new GitMaterial(UUID.randomUUID().toString(), "branch"));
    final ArrayList<Modification> firstSetOfModifications = getModifications(3);
    transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            repo.saveModifications(materialInstance, firstSetOfModifications);
            return null;
        }
    });
    Modifications firstSetOfModificationsFromDb = repo.getModificationsFor(materialInstance, Pagination.pageByNumber(1, 10, 10));
    assertThat(firstSetOfModificationsFromDb.size(), is(3));
    for (Modification modification : firstSetOfModifications) {
        assertThat(firstSetOfModificationsFromDb.containsRevisionFor(modification), is(true));
    }
    final ArrayList<Modification> secondSetOfModificationsContainingDuplicateRevisions = getModifications(4);
    transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            repo.saveModifications(materialInstance, secondSetOfModificationsContainingDuplicateRevisions);
            return null;
        }
    });
    Modifications secondSetOfModificationsFromDb = repo.getModificationsFor(materialInstance, Pagination.pageByNumber(1, 10, 10));
    assertThat(secondSetOfModificationsFromDb.size(), is(4));
    for (final Modification fromPreviousCycle : firstSetOfModificationsFromDb) {
        Modification modification = secondSetOfModificationsFromDb.stream().filter(new Predicate<Modification>() {

            @Override
            public boolean test(Modification item) {
                return item.getId() == fromPreviousCycle.getId();
            }
        }).findFirst().orElse(null);
        assertThat(modification, is(notNullValue()));
    }
    for (Modification modification : secondSetOfModificationsContainingDuplicateRevisions) {
        assertThat(secondSetOfModificationsFromDb.containsRevisionFor(modification), is(true));
    }
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) GitMaterial(com.thoughtworks.go.config.materials.git.GitMaterial) TransactionStatus(org.springframework.transaction.TransactionStatus) P4MaterialInstance(com.thoughtworks.go.domain.materials.perforce.P4MaterialInstance) PackageMaterialInstance(com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance) TfsMaterialInstance(com.thoughtworks.go.domain.materials.tfs.TfsMaterialInstance) HgMaterialInstance(com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance) PluggableSCMMaterialInstance(com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance) SvnMaterialInstance(com.thoughtworks.go.domain.materials.svn.SvnMaterialInstance) Test(org.junit.jupiter.api.Test)

Example 30 with TransactionCallback

use of org.springframework.transaction.support.TransactionCallback in project gocd by gocd.

the class MaterialRepositoryIntegrationTest method shouldBeAbleToHandleLargeNumberOfModifications.

// Slow test - takes ~1 min to run. Will remove if it causes issues. - Jyoti
@Test
public void shouldBeAbleToHandleLargeNumberOfModifications() {
    final MaterialInstance materialInstance = repo.findOrCreateFrom(new GitMaterial(UUID.randomUUID().toString(), "branch"));
    int count = 10000;
    final ArrayList<Modification> firstSetOfModifications = getModifications(count);
    transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            repo.saveModifications(materialInstance, firstSetOfModifications);
            return null;
        }
    });
    assertThat(repo.getTotalModificationsFor(materialInstance), is(new Long(count)));
    final ArrayList<Modification> secondSetOfModifications = getModifications(count + 1);
    transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            repo.saveModifications(materialInstance, secondSetOfModifications);
            return null;
        }
    });
    assertThat(repo.getTotalModificationsFor(materialInstance), is(new Long(count + 1)));
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) GitMaterial(com.thoughtworks.go.config.materials.git.GitMaterial) TransactionStatus(org.springframework.transaction.TransactionStatus) P4MaterialInstance(com.thoughtworks.go.domain.materials.perforce.P4MaterialInstance) PackageMaterialInstance(com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance) TfsMaterialInstance(com.thoughtworks.go.domain.materials.tfs.TfsMaterialInstance) HgMaterialInstance(com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance) PluggableSCMMaterialInstance(com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance) SvnMaterialInstance(com.thoughtworks.go.domain.materials.svn.SvnMaterialInstance) Test(org.junit.jupiter.api.Test)

Aggregations

TransactionCallback (org.springframework.transaction.support.TransactionCallback)101 TransactionStatus (org.springframework.transaction.TransactionStatus)76 Test (org.junit.Test)28 ArrayList (java.util.ArrayList)16 Test (org.junit.jupiter.api.Test)14 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)11 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)10 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)9 PreparedStatement (java.sql.PreparedStatement)8 List (java.util.List)8 GitMaterial (com.thoughtworks.go.config.materials.git.GitMaterial)7 MaterialInstance (com.thoughtworks.go.domain.MaterialInstance)7 Modification (com.thoughtworks.go.domain.materials.Modification)7 PackageMaterialInstance (com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance)7 PluggableSCMMaterialInstance (com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance)7 Query (org.hibernate.Query)7 BaseDbTest (com.alibaba.otter.node.etl.BaseDbTest)6 DbDialect (com.alibaba.otter.node.etl.common.db.dialect.DbDialect)6 Modifications (com.thoughtworks.go.domain.materials.Modifications)6 HgMaterialInstance (com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance)6