org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRED

Here are the examples of the java api org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRED taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

52 Examples 7

19 View Source File : WebSphereUowTransactionManagerTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void newTransactionWithCommitUsingPropagationRequiredAndSynchNever() {
    doTestNewTransactionWithCommit(TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER);
}

19 View Source File : WebSphereUowTransactionManagerTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void existingTransactionWithParticipationUsingPropagationRequired() {
    doTestExistingTransactionWithParticipation(TransactionDefinition.PROPAGATION_REQUIRED);
}

19 View Source File : WebSphereUowTransactionManagerTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void newTransactionWithCommitUsingPropagationRequired() {
    doTestNewTransactionWithCommit(TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS);
}

19 View Source File : WebSphereUowTransactionManagerTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void newTransactionWithCommitUsingPropagationRequiredAndSynchOnActual() {
    doTestNewTransactionWithCommit(TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
}

19 View Source File : ProductServiceImpl2.java
License : Apache License 2.0
Project Creator : penggle

@Override
public void updateProduct(final Product product) {
    TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.executeWithoutResult(transactionStatus -> {
        productRepository.updateProduct(product);
        accessLogService.recordAccessLog2(new AccessLog("更新商品", "updateProduct()", DateTimeUtils.formatNow()));
    // throw new IllegalStateException("Intentional Exception!"); //父事务因异常而回滚不会影响子事务
    });
}

19 View Source File : ProductServiceImpl2.java
License : Apache License 2.0
Project Creator : penggle

@Override
public void deleteProductById(final Long productId) {
    TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.executeWithoutResult(transactionStatus -> {
        productRepository.deleteProductById(productId);
        accessLogService.recordAccessLog1(new AccessLog("删除商品", "deleteProductById()", DateTimeUtils.formatNow()));
    });
}

19 View Source File : AbstractAsgardConsumer.java
License : Apache License 2.0
Project Creator : open-hand

protected TransactionStatus createTransactionStatus(final PlatformTransactionManager transactionManager, final int isolationLevel) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(isolationLevel);
    return transactionManager.getTransaction(def);
}

19 View Source File : AlphaService.java
License : Apache License 2.0
Project Creator : cosen1024

public Object save2() {
    transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return transactionTemplate.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            // 新增用户
            User user = new User();
            user.setUsername("beta");
            user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
            user.setPreplacedword(CommunityUtil.md5("123" + user.getSalt()));
            user.setEmail("[email protected]");
            user.setHeaderUrl("http://image.nowcoder.com/head/999t.png");
            user.setCreateTime(new Date());
            userMapper.insertUser(user);
            // 新增帖子
            DiscussPost post = new DiscussPost();
            post.setUserId(user.getId());
            post.setreplacedle("你好");
            post.setContent("我是新人!");
            post.setCreateTime(new Date());
            discussPostMapper.insertDiscussPost(post);
            Integer.valueOf("abc");
            return "ok";
        }
    });
}

18 View Source File : TransactionAttributeSourceEditorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void matchesAll() throws Exception {
    editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED");
    TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();
    checkTransactionProperties(tas, Object.clreplaced.getMethod("hashCode"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("equals", Object.clreplaced), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", long.clreplaced), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", long.clreplaced, int.clreplaced), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notify"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notifyAll"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("toString"), TransactionDefinition.PROPAGATION_REQUIRED);
}

18 View Source File : ProductServiceImpl2.java
License : Apache License 2.0
Project Creator : penggle

@Override
public void createProduct(final Product product) {
    TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.executeWithoutResult(transactionStatus -> {
        productRepository.createProduct(product);
        accessLogService.recordAccessLog1(new AccessLog("新增商品", "createProduct()", DateTimeUtils.formatNow()));
    });
}

18 View Source File : AbstractFinalMessageProcessor.java
License : Apache License 2.0
Project Creator : OpenWiseSolutions

@PostConstruct
void initializeTransactionManager() {
    this.transactionTemplate = new TransactionTemplate(transactionManager);
    this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
}

18 View Source File : TransactionAttributeSourceEditorTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void matchesAll() throws Exception {
    editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED");
    TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();
    checkTransactionProperties(tas, Object.clreplaced.getMethod("hashCode", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("equals", new Clreplaced[] { Object.clreplaced }), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", new Clreplaced[] { long.clreplaced }), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", new Clreplaced[] { long.clreplaced, int.clreplaced }), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notify", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notifyAll", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("toString", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
}

18 View Source File : CalendarTableModel.java
License : GNU General Public License v3.0
Project Creator : bcgov

/**
 * Сохранить календарь.
 */
public void save() {
    QLog.l().logger().info("Save the calendar ID = " + calcId);
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
    try {
        final LinkedList<FreeDay> dels = new LinkedList<>();
        for (FreeDay bad : days_del) {
            boolean f = true;
            for (FreeDay good : days) {
                if (good.equals(bad)) {
                    f = false;
                }
            }
            if (f) {
                dels.add(bad);
            }
        }
        Spring.getInstance().getHt().deleteAll(dels);
        Spring.getInstance().getHt().saveOrUpdateAll(days);
    } catch (Exception ex) {
        Spring.getInstance().getTxManager().rollback(status);
        throw new ClientException("Error performing the operation of modifying data in the database (JDBC).\nPerhaps you added a new calendar, changed it, tried to save the contents of the calendar, but did not save the overall configuration.\nSave the entire configuration (Ctrl + S) and try again to save the contents of the calendar.\n\n[" + ex.getLocalizedMessage() + "]\n(" + ex.toString() + ")");
    }
    Spring.getInstance().getTxManager().commit(status);
    QLog.l().logger().debug("Saved a new calendar");
    // Type so that there are actual internal data
    days_del = new ArrayList<>(days);
}

17 View Source File : TransactionConfig.java
License : MIT License
Project Creator : yizzuide

@Bean
public TransactionInterceptor txAdvice(PlatformTransactionManager transactionManager) {
    RuleBasedTransactionAttribute txAttr_REQUIRED = new RuleBasedTransactionAttribute();
    // 设置传播行为:若当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。这是默认值。
    txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    // 抛出异常后执行切点回滚
    txAttr_REQUIRED.setRollbackRules(props.getRollbackWhenException().stream().map(RollbackRuleAttribute::new).collect(Collectors.toList()));
    // 设置超时
    txAttr_REQUIRED.setTimeout((int) props.getRollbackWhenTimeout().getSeconds());
    RuleBasedTransactionAttribute txAttr_REQUIRED_READONLY = new RuleBasedTransactionAttribute();
    txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    txAttr_REQUIRED_READONLY.setReadOnly(true);
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    // 开启只读, 提高数据库访问性能
    if (!CollectionUtils.isEmpty(props.getReadOnlyPrefix())) {
        for (String prefix : props.getReadOnlyPrefix()) {
            source.addTransactionalMethod(prefix, txAttr_REQUIRED_READONLY);
        }
    }
    if (!CollectionUtils.isEmpty(props.getReadOnlyAppendPrefix())) {
        for (String prefix : props.getReadOnlyAppendPrefix()) {
            source.addTransactionalMethod(prefix, txAttr_REQUIRED_READONLY);
        }
    }
    // 其它都需要事务
    source.addTransactionalMethod("*", txAttr_REQUIRED);
    return new TransactionInterceptor(transactionManager, source);
}

17 View Source File : TransactionAttributeSourceEditorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void matchesSpecific() throws Exception {
    editor.setAsText("java.lang.Object.hashCode=PROPAGATION_REQUIRED\n" + "java.lang.Object.equals=PROPAGATION_MANDATORY\n" + "java.lang.Object.*it=PROPAGATION_SUPPORTS\n" + "java.lang.Object.notify=PROPAGATION_SUPPORTS\n" + "java.lang.Object.not*=PROPAGATION_REQUIRED");
    TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();
    checkTransactionProperties(tas, Object.clreplaced.getMethod("hashCode"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("equals", Object.clreplaced), TransactionDefinition.PROPAGATION_MANDATORY);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait"), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", long.clreplaced), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", long.clreplaced, int.clreplaced), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notify"), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notifyAll"), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("toString"), -1);
}

17 View Source File : TransactionAttributeSourceEditorTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void matchesSpecific() throws Exception {
    editor.setAsText("java.lang.Object.hashCode=PROPAGATION_REQUIRED\n" + "java.lang.Object.equals=PROPAGATION_MANDATORY\n" + "java.lang.Object.*it=PROPAGATION_SUPPORTS\n" + "java.lang.Object.notify=PROPAGATION_SUPPORTS\n" + "java.lang.Object.not*=PROPAGATION_REQUIRED");
    TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();
    checkTransactionProperties(tas, Object.clreplaced.getMethod("hashCode", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("equals", new Clreplaced[] { Object.clreplaced }), TransactionDefinition.PROPAGATION_MANDATORY);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", new Clreplaced[] { long.clreplaced }), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("wait", new Clreplaced[] { long.clreplaced, int.clreplaced }), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notify", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_SUPPORTS);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("notifyAll", (Clreplaced[]) null), TransactionDefinition.PROPAGATION_REQUIRED);
    checkTransactionProperties(tas, Object.clreplaced.getMethod("toString", (Clreplaced[]) null), -1);
}

17 View Source File : SpringHibernateDataStore.java
License : Apache License 2.0
Project Creator : illyasviel

@Override
public DataStoreTransaction beginTransaction() {
    // begin a spring transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("elide transaction");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus txStatus = txManager.getTransaction(def);
    Session session = enreplacedyManager.unwrap(Session.clreplaced);
    Preconditions.checkNotNull(session);
    return transactionSupplier.get(session, txManager, txStatus, isScrollEnabled, scrollMode);
}

17 View Source File : AdminGoodsController.java
License : MIT License
Project Creator : geekyouth

@PostMapping("/delete")
public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallGoods goods) {
    if (adminId == null) {
        return ResponseUtil.unlogin();
    }
    // 开启事务管理
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txManager.getTransaction(def);
    try {
        Integer gid = goods.getId();
        goodsService.deleteById(gid);
        specificationService.deleteByGid(gid);
        attributeService.deleteByGid(gid);
        productService.deleteByGid(gid);
    } catch (Exception ex) {
        txManager.rollback(status);
        logger.error("系统内部错误", ex);
    }
    txManager.commit(status);
    return ResponseUtil.ok();
}

17 View Source File : InsideCompensationHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : dromara

/**
 * 处理补偿内嵌的远程方法的时候,不提交,只调用.
 *
 * @param point point 切点
 * @param info  信息
 * @return Object
 * @throws Throwable 异常
 */
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    PlatformTransactionManager platformTransactionManager = TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
    TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
    try {
        return point.proceed();
    } finally {
        platformTransactionManager.rollback(transactionStatus);
    }
}

16 View Source File : TransactionalConfig.java
License : Apache License 2.0
Project Creator : yujunhao8831

/**
 * 支持当前事务;如果不存在创建一个新的
 * {@link org.springframework.transaction.annotation.Propagation#REQUIRED}
 */
private RuleBasedTransactionAttribute requiredTransactionRule() {
    RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute();
    required.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.clreplaced)));
    required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    required.setTimeout(TransactionDefinition.TIMEOUT_DEFAULT);
    return required;
}

16 View Source File : TransactionalConfig.java
License : Apache License 2.0
Project Creator : yujunhao8831

/**
 * 支持当前事务;如果不存在创建一个新的
 */
private RuleBasedTransactionAttribute requiredTransactionRule() {
    RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute();
    required.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.clreplaced)));
    required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    required.setTimeout(TransactionDefinition.TIMEOUT_DEFAULT);
    return required;
}

16 View Source File : OracleDatabaseInitializer.java
License : MIT License
Project Creator : yoomoney-tech

public static synchronized void initialize() {
    if (oraJdbcTemplate != null) {
        return;
    }
    String ryukImage = Optional.ofNullable(System.getProperty("testcontainers.ryuk.container.image")).orElse("quay.io/testcontainers/ryuk:0.2.3");
    TestcontainersConfiguration.getInstance().updateGlobalConfig("ryuk.container.image", ryukImage);
    String oracleImage = Optional.ofNullable(System.getProperty("testcontainers.oracle.container.image")).orElse("wnameless/oracle-xe-11g-r2");
    OracleContainer dbContainer = new OracleContainer(oracleImage);
    dbContainer.start();
    addUserAndSchema(dbContainer, "oracle_test");
    OracleDataSource dataSource = getDataSource(dbContainer, "oracle_test");
    oraJdbcTemplate = new JdbcTemplate(dataSource);
    oraTransactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    oraTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    oraTransactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    executeDdl("CREATE SEQUENCE tasks_seq START WITH 1");
    createTable(ORA_DEFAULT_TABLE_DDL, DEFAULT_TABLE_NAME);
    createTable(ORA_CUSTOM_TABLE_DDL, CUSTOM_TABLE_NAME);
}

16 View Source File : TransactionAttributeSourceTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void nameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() throws Exception {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("hashCod*", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode"), null);
    replacedertNotNull(ta);
    replacedertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}

16 View Source File : TransactionAttributeSourceTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void nameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() throws Exception {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("*ashCode", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode"), null);
    replacedertNotNull(ta);
    replacedertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}

16 View Source File : TransactionAttributeSourceTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void nameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() throws Exception {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("hashCod*", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode"), null);
    replacedertThat(ta).isNotNull();
    replacedertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED);
}

16 View Source File : TransactionAttributeSourceTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void nameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() throws Exception {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("*ashCode", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode"), null);
    replacedertThat(ta).isNotNull();
    replacedertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED);
}

16 View Source File : TransactionAttributeSourceTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void nameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() throws NoSuchMethodException {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("*ashCode", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode", (Clreplaced[]) null), null);
    replacedertNotNull(ta);
    replacedertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}

16 View Source File : TransactionAttributeSourceTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void nameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() throws NoSuchMethodException {
    NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
    Properties attributes = new Properties();
    attributes.put("hashCod*", "PROPAGATION_REQUIRED");
    tas.setProperties(attributes);
    TransactionAttribute ta = tas.getTransactionAttribute(Object.clreplaced.getMethod("hashCode", (Clreplaced[]) null), null);
    replacedertNotNull(ta);
    replacedertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}

16 View Source File : FastTransaction.java
License : GNU General Public License v3.0
Project Creator : kaixinzyw

/**
 * 开启事务
 */
public static void open() {
    TransactionInfo transaction = getTransactionInfo();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transaction.setStatus(transaction.getTran().getTransaction(def));
}

16 View Source File : AdminOrderController.java
License : MIT License
Project Creator : geekyouth

/**
 * 自动取消订单
 * <p>
 * 定时检查订单未付款情况,如果超时半个小时则自动取消订单
 * 定时时间是每次相隔半个小时。
 * <p>
 * 注意,因为是相隔半小时检查,因此导致有订单是超时一个小时以后才设置取消状态。
 * TODO
 * 这里可以进一步地配合用户订单查询时订单未付款检查,如果订单超时半小时则取消。
 */
@Scheduled(fixedDelay = 30 * 60 * 1000)
public void checkOrderUnpaid() {
    logger.debug(LocalDateTime.now());
    List<LitemallOrder> orderList = orderService.queryUnpaid();
    for (LitemallOrder order : orderList) {
        LocalDateTime add = order.getAddTime();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expired = add.plusMinutes(30);
        if (expired.isAfter(now)) {
            continue;
        }
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {
            // 设置订单已取消状态
            order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
            order.setEndTime(LocalDateTime.now());
            orderService.updateById(order);
            // 商品货品数量增加
            Integer orderId = order.getId();
            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
            for (LitemallOrderGoods orderGoods : orderGoodsList) {
                Integer productId = orderGoods.getProductId();
                LitemallProduct product = productService.findById(productId);
                Integer number = product.getNumber() + orderGoods.getNumber();
                product.setNumber(number);
                productService.updateById(product);
            }
        } catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);
    }
}

16 View Source File : SpringDataMongoV3Driver.java
License : Apache License 2.0
Project Creator : cloudyrock

private TransactionStatus getTxStatus(MongoTransactionManager txManager) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    // explicitly setting the transaction name is something that can be done only programmatically
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return txManager.getTransaction(def);
}

16 View Source File : SpringDataMongoV2Driver.java
License : Apache License 2.0
Project Creator : cloudyrock

private TransactionStatus getTxStatus(MongoTransactionManager txManager) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return txManager.getTransaction(def);
}

16 View Source File : PersistHelper.java
License : Apache License 2.0
Project Creator : alibaba

private TransactionStatus getTransactionStatus() {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    return transactionManager.getTransaction(definition);
}

15 View Source File : TransactionConfiguration.java
License : Apache License 2.0
Project Creator : zhuoqianmingyue

@Bean
public TransactionInterceptor txAdvice() {
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    /* 只读事务,不做更新操作 */
    RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
    readOnlyTx.setReadOnly(true);
    readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
    /* 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务 */
    RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
    requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.clreplaced)));
    requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    // requiredTx.setTimeout(TX_METHOD_TIMEOUT);
    Map<String, TransactionAttribute> txMap = new HashMap<String, TransactionAttribute>();
    txMap.put("add*", requiredTx);
    txMap.put("save*", requiredTx);
    txMap.put("insert*", requiredTx);
    txMap.put("update*", requiredTx);
    txMap.put("delete*", requiredTx);
    txMap.put("get*", readOnlyTx);
    txMap.put("find*", readOnlyTx);
    txMap.put("query*", readOnlyTx);
    txMap.put("*", requiredTx);
    source.setNameMap(txMap);
    TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
    return txAdvice;
}

15 View Source File : FixAttachFeature330.java
License : Apache License 2.0
Project Creator : inception-project

private void doMigration() {
    long start = System.currentTimeMillis();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("migrationRoot");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = null;
    try {
        status = txManager.getTransaction(def);
        for (Project project : projectService.listProjects()) {
            try {
                AnnotationLayer tokenLayer = annotationSchemaService.findLayer(project, Token.clreplaced.getName());
                // Set attach-feature of Dependency layer to Token.pos if necessary
                fix(project, Dependency.clreplaced, RELATION_TYPE, tokenLayer, "pos");
                // Set attach-feature of POS layer to Token.pos if necessary
                fix(project, POS.clreplaced, SPAN_TYPE, tokenLayer, "pos");
                // Set attach-feature of Lemma layer to Token.lemma if necessary
                fix(project, Lemma.clreplaced, SPAN_TYPE, tokenLayer, "lemma");
                // Set attach-feature of MorphologicalFeatures layer to Token.morph if necessary
                fix(project, MorphologicalFeatures.clreplaced, SPAN_TYPE, tokenLayer, "morph");
            } catch (NoResultException e) {
                // This only happens if a project is not fully set up. Every project
                // should have a Token layer. However, it is not the responsibility of this
                // migration to enforce this, so we just ignore it.
                log.warn("Project {} does not seem to include a Token layer!", project);
            }
        }
        txManager.commit(status);
    } finally {
        if (status != null && !status.isCompleted()) {
            txManager.rollback(status);
        }
    }
    log.info("Migration [" + getClreplaced().getSimpleName() + "] took {}ms", System.currentTimeMillis() - start);
}

15 View Source File : TransactionAspect.java
License : GNU General Public License v3.0
Project Creator : gxing19

@Bean
public TransactionInterceptor txAdvice() {
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    // 只读事务,不做更新操作
    RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
    readOnlyTx.setReadOnly(true);
    // 以非事务方式执行
    readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
    // 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务
    RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
    requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.clreplaced)));
    requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    requiredTx.setTimeout(TX_METHOD_TIMEOUT);
    Map<String, TransactionAttribute> txMap = new HashMap<>();
    // 事务方法前缀
    txMap.put("add*", requiredTx);
    txMap.put("save*", requiredTx);
    txMap.put("insert*", requiredTx);
    txMap.put("update*", requiredTx);
    txMap.put("delete*", requiredTx);
    txMap.put("remove*", requiredTx);
    // 非事务方法前缀
    txMap.put("get*", readOnlyTx);
    txMap.put("find*", readOnlyTx);
    txMap.put("select*", readOnlyTx);
    txMap.put("query*", readOnlyTx);
    source.setNameMap(txMap);
    TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
    return txAdvice;
}

14 View Source File : MssqlDatabaseInitializer.java
License : MIT License
Project Creator : yoomoney-tech

public static synchronized void initialize() {
    if (msJdbcTemplate != null) {
        return;
    }
    SQLServerDataSource dataSource;
    String ryukImage = Optional.ofNullable(System.getProperty("testcontainers.ryuk.container.image")).orElse("quay.io/testcontainers/ryuk:0.2.3");
    TestcontainersConfiguration.getInstance().updateGlobalConfig("ryuk.container.image", ryukImage);
    String mssqlImage = Optional.ofNullable(System.getProperty("testcontainers.mssql.container.image")).orElse("mcr.microsoft.com/mssql/server:2019-CU1-ubuntu-16.04");
    MSSQLServerContainer containerInstance = new MSSQLServerContainer<>(mssqlImage);
    containerInstance.start();
    URI uri = URI.create(containerInstance.getJdbcUrl().substring(5));
    dataSource = new SQLServerDataSource();
    dataSource.setServerName(uri.getHost());
    dataSource.setPortNumber(uri.getPort());
    dataSource.setUser(containerInstance.getUsername());
    dataSource.setPreplacedword(containerInstance.getPreplacedword());
    msJdbcTemplate = new JdbcTemplate(dataSource);
    msTransactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    msTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    msTransactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    executeDdl("CREATE SEQUENCE tasks_seq START WITH 1");
    createTable(MS_DEFAULT_TABLE_DDL, DEFAULT_TABLE_NAME);
    createTable(MS_DEFAULT_WO_IDENT_TABLE_DDL, DEFAULT_TABLE_NAME_WO_IDENT);
    createTable(MS_CUSTOM_TABLE_DDL, CUSTOM_TABLE_NAME);
}

14 View Source File : AdminOrderController.java
License : MIT License
Project Creator : geekyouth

/**
 * 订单退款确认
 * 1. 检测当前订单是否能够退款确认
 * 2. 设置订单退款确认状态
 * 3. 订单商品恢复
 *
 * @param adminId 管理员ID
 * @param body    订单信息,{ orderId:xxx }
 * @return 订单操作结果
 * 成功则 { errno: 0, errmsg: '成功' }
 * 失败则 { errno: XXX, errmsg: XXX }
 */
@PostMapping("refund")
public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) {
    if (adminId == null) {
        return ResponseUtil.unlogin();
    }
    Integer orderId = JacksonUtil.parseInteger(body, "orderId");
    String refundMoney = JacksonUtil.parseString(body, "refundMoney");
    if (orderId == null) {
        return ResponseUtil.badArgument();
    }
    LitemallOrder order = orderService.findById(orderId);
    if (order == null) {
        return ResponseUtil.badArgument();
    }
    if (order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0) {
        return ResponseUtil.badArgumentValue();
    }
    // 如果订单不是退款状态,则不能退款
    if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) {
        return ResponseUtil.fail(403, "订单不能确认收货");
    }
    // 开启事务管理
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txManager.getTransaction(def);
    try {
        // 设置订单取消状态
        order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM);
        orderService.update(order);
        // 商品货品数量增加
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Integer productId = orderGoods.getProductId();
            LitemallProduct product = productService.findById(productId);
            Integer number = product.getNumber() + orderGoods.getNumber();
            product.setNumber(number);
            productService.updateById(product);
        }
    } catch (Exception ex) {
        txManager.rollback(status);
        logger.error("系统内部错误", ex);
        return ResponseUtil.fail(403, "订单退款失败");
    }
    // TODO 发送邮件和短信通知,这里采用异步发送
    // 退款成功通知用户
    /**
     * 您申请的订单退款 [ 单号:{1} ] 已成功,请耐心等待到账。
     * 注意订单号只发后6位
     */
    notifyService.notifySmsTemplate(order.getMobile(), NotifyType.REFUND, new String[] { order.getOrderSn().substring(8, 14) });
    txManager.commit(status);
    return ResponseUtil.ok();
}

14 View Source File : AdminGoodsController.java
License : MIT License
Project Creator : geekyouth

/*
     * TODO
     * 目前商品修改的逻辑是
     * 1. 更新litemall_goods表
     * 2. 逻辑删除litemall_goods_specification、litemall_goods_attribute、litemall_product
     * 3. 添加litemall_goods_specification、litemall_goods_attribute、litemall_product
     *
     * 这里商品三个表的数据采用删除再跟新的策略是因为
     * 商品编辑页面,管理员可以添加删除商品规格、添加删除商品属性,因此这里仅仅更新表是不可能的,
     * 因此这里只能删除所有旧的数据,然后添加新的数据
     */
@PostMapping("/update")
public Object update(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) {
    if (adminId == null) {
        return ResponseUtil.unlogin();
    }
    LitemallGoods goods = goodsAllinone.getGoods();
    LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
    LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
    LitemallProduct[] products = goodsAllinone.getProducts();
    // 开启事务管理
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txManager.getTransaction(def);
    try {
        // 将生成的分享图片地址写入数据库
        qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        goods.setShareUrl(qCodeService.getShareImageUrl(goods.getId().toString()));
        // 商品基本信息表litemall_goods
        goodsService.updateById(goods);
        Integer gid = goods.getId();
        specificationService.deleteByGid(gid);
        attributeService.deleteByGid(gid);
        productService.deleteByGid(gid);
        // 商品规格表litemall_goods_specification
        Map<String, Integer> specIds = new HashMap<>();
        for (LitemallGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specification.setAddTime(LocalDateTime.now());
            specificationService.add(specification);
            specIds.put(specification.getValue(), specification.getId());
        }
        // 商品参数表litemall_goods_attribute
        for (LitemallGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attribute.setAddTime(LocalDateTime.now());
            attributeService.add(attribute);
        }
        // 商品货品表litemall_product
        for (LitemallProduct product : products) {
            product.setGoodsId(goods.getId());
            product.setAddTime(LocalDateTime.now());
            productService.add(product);
        }
    } catch (Exception ex) {
        txManager.rollback(status);
        logger.error("系统内部错误", ex);
    }
    txManager.commit(status);
    qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
    return ResponseUtil.ok();
}

14 View Source File : TransactionAdviceConfig.java
License : Apache License 2.0
Project Creator : drinkagain

@Bean
public TransactionInterceptor txAdvice() {
    DefaultTransactionAttribute required = new DefaultTransactionAttribute();
    required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    DefaultTransactionAttribute readonly = new DefaultTransactionAttribute();
    readonly.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    readonly.setReadOnly(true);
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    source.addTransactionalMethod("add*", required);
    source.addTransactionalMethod("save*", required);
    source.addTransactionalMethod("delete*", required);
    source.addTransactionalMethod("update*", required);
    source.addTransactionalMethod("exec*", required);
    source.addTransactionalMethod("set*", required);
    source.addTransactionalMethod("do*", required);
    source.addTransactionalMethod("get*", readonly);
    source.addTransactionalMethod("query*", readonly);
    source.addTransactionalMethod("find*", readonly);
    source.addTransactionalMethod("list*", readonly);
    source.addTransactionalMethod("count*", readonly);
    return new TransactionInterceptor(transactionManager, source);
}

14 View Source File : SpringTransactionRunner.java
License : Apache License 2.0
Project Creator : crnk-project

@Override
public <T> T doInTransaction(final Callable<T> callable) {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionTemplate template = new TransactionTemplate(platformTransactionManager, definition);
    try {
        return template.execute(new TransactionCallback<T>() {

            @Override
            public T doInTransaction(TransactionStatus status) {
                try {
                    T result = callable.call();
                    if (status.isRollbackOnly()) {
                        // TransactionTemplate does not properly deal with Rollback exceptions
                        // an exception is required, otherwise it will attempt to commit again
                        throw new RollbackOnlyException(result);
                    }
                    return result;
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });
    } catch (RollbackOnlyException e) {
        return (T) e.getResult();
    }
}

14 View Source File : AlarmAdminService.java
License : MIT License
Project Creator : AutohomeCorp

public boolean atomicSave(AlarmContract alarmContract) {
    boolean isValidCron = CronExpression.isValidExpression(alarmContract.getCron());
    if (!isValidCron) {
        throw new ProtocolException(510, "cron表达式非法");
    }
    padAlarm(alarmContract);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = frostmourneTransactionManager.getTransaction(def);
    try {
        save(alarmContract);
    } catch (Exception ex) {
        frostmourneTransactionManager.rollback(status);
        LOGGER.error("error when save alarm", ex);
        throw ex;
    }
    frostmourneTransactionManager.commit(status);
    return true;
}

13 View Source File : AccessLogServiceImpl2.java
License : Apache License 2.0
Project Creator : penggle

@Override
public void recordAccessLog1(final AccessLog accessLog) {
    TransactionTemplate transactionTemplate = transactionTemplateFactory.createTransactionTemplate(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.executeWithoutResult(transactionStatus -> {
        accessLogRepository.recordAccessLog1(accessLog);
    /**
     * 不通过抛出业务异常来回滚,而直接通过标记rollbackOnly=true来强制回滚当前事务;PROPAGATION_REQUIRES_NEW时,子事务回滚不会影响父事务.
     * 与下面不同的是,这个会导致UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
     * 这是因为在当前事务传播语义下,一旦某个事务标记rollback-only为true那么将会导致global-rollback-only也为true,所以会抛出异常
     * 但是此异常并不是导致事物回滚的原因,事务是主动回滚的,而不是依靠此UnexpectedRollbackException被动回滚的,这点需要明白。
     */
    // transactionStatus.setRollbackOnly();
    });
}

13 View Source File : FixCoreferenceFeatures.java
License : Apache License 2.0
Project Creator : inception-project

private void doMigration() {
    long start = System.currentTimeMillis();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("migrationRoot");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = null;
    try {
        status = txManager.getTransaction(def);
        // @formatter:off
        Query q = enreplacedyManager.createQuery("UPDATE AnnotationFeature \n" + "SET type = :fixedType \n" + "WHERE type = :oldType \n" + "AND name in (:featureNames)");
        // @formatter:on
        // This condition cannot be applied:
        // "AND layer.type = :layerType"
        // q.setParameter("layerType", CHAIN_TYPE);
        // http://stackoverflow.com/questions/16506759/hql-is-generating-incomplete-cross-join-on-executeupdate
        // However, the risk that the migration upgrades the wrong featuers is still very low
        // even without this additional condition
        q.setParameter("featureNames", Arrays.asList(COREFERENCE_RELATION_FEATURE, COREFERENCE_TYPE_FEATURE));
        q.setParameter("oldType", "de.tudarmstadt.ukp.dkpro.core.api.coref.type.Coreference");
        q.setParameter("fixedType", CAS.TYPE_NAME_STRING);
        int changed = q.executeUpdate();
        if (changed > 0) {
            log.info("DATABASE UPGRADE PERFORMED: [{}] coref chain features had their " + "type fixed.", changed);
        }
        txManager.commit(status);
    } finally {
        if (status != null && !status.isCompleted()) {
            txManager.rollback(status);
        }
    }
    log.info("Migration [" + getClreplaced().getSimpleName() + "] took {}ms", System.currentTimeMillis() - start);
}

13 View Source File : AdminGoodsController.java
License : MIT License
Project Creator : geekyouth

@PostMapping("/create")
public Object create(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) {
    if (adminId == null) {
        return ResponseUtil.unlogin();
    }
    LitemallGoods goods = goodsAllinone.getGoods();
    LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
    LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
    LitemallProduct[] products = goodsAllinone.getProducts();
    String name = goods.getName();
    if (goodsService.checkExistByName(name)) {
        return ResponseUtil.fail(403, "商品名已经存在");
    }
    // 开启事务管理
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txManager.getTransaction(def);
    try {
        // 商品基本信息表litemall_goods
        goods.setAddTime(LocalDateTime.now());
        goodsService.add(goods);
        // 将生成的分享图片地址写入数据库
        qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        goods.setShareUrl(qCodeService.getShareImageUrl(goods.getId().toString()));
        goodsService.updateById(goods);
        // 商品规格表litemall_goods_specification
        Map<String, Integer> specIds = new HashMap<>();
        for (LitemallGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specification.setAddTime(LocalDateTime.now());
            specificationService.add(specification);
            specIds.put(specification.getValue(), specification.getId());
        }
        // 商品参数表litemall_goods_attribute
        for (LitemallGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attribute.setAddTime(LocalDateTime.now());
            attributeService.add(attribute);
        }
        // 商品货品表litemall_product
        for (LitemallProduct product : products) {
            product.setGoodsId(goods.getId());
            product.setAddTime(LocalDateTime.now());
            productService.add(product);
        }
    } catch (Exception ex) {
        txManager.rollback(status);
        logger.error("系统内部错误", ex);
    }
    txManager.commit(status);
    return ResponseUtil.ok();
}

12 View Source File : TransactionAttributeSourceTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void matchAlwaysTransactionAttributeSourceWithNulls() throws Exception {
    MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource();
    TransactionDefinition definition = tas.getTransactionAttribute(null, null);
    replacedertEquals(TransactionDefinition.PROPAGATION_REQUIRED, definition.getPropagationBehavior());
    replacedertEquals(TransactionDefinition.ISOLATION_DEFAULT, definition.getIsolationLevel());
    replacedertEquals(TransactionDefinition.TIMEOUT_DEFAULT, definition.getTimeout());
    replacedertFalse(definition.isReadOnly());
}

12 View Source File : QCustomer.java
License : GNU General Public License v3.0
Project Creator : bcgov

private void saveToSelfDB() {
    // ???????? ????????? ? ????
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
    try {
        if (input_data == null) {
            // ??? ??? ???? ?????? ????????? ?????????? ?? ?? ??? ????????? ?????? ?? ???, ? ??? ???? ???? ????? ?????
            // /Here is the same zhed by the pull of the pull to set the contention that the entered data is not zero, and they rarely need this input
            input_data = "";
        }
        List<Integer> finishStates = Arrays.asList(0, 10, 13);
        if (finishStates.contains(getStateIn())) {
            // QLog.l().logQUser().info("Client is in finish state, clear comments...");
            setTempComments("");
        }
        Spring.getInstance().getHt().saveOrUpdate(this);
        // QLog.l().logQUser().info("Saved customer");
        // ???????. ???? ???????? ??????? ?????? ?????? ??? ????? ? ??, ?.?. ?? ????? ?????? ??? ? ???.
        // Crutch. If the customizer left a comment before getting into the database, ie. While working with him.
        if (resps.size() > 0) {
            Spring.getInstance().getHt().saveAll(resps);
            resps.clear();
        }
    } catch (Exception ex) {
        Spring.getInstance().getTxManager().rollback(status);
        throw new ServerException("?????? ??? ?????????? :: Error while saving \n" + ex.toString() + "\n" + Arrays.toString(ex.getStackTrace()));
    }
    Spring.getInstance().getTxManager().commit(status);
// QLog.l().logger().debug("?????????.");
}

12 View Source File : AlarmAdminService.java
License : MIT License
Project Creator : AutohomeCorp

public boolean delete(Long alarmId) {
    Optional<Alarm> optionalAlarm = alarmRepository.selectByPrimaryKey(alarmId);
    if (!optionalAlarm.isPresent()) {
        return false;
    }
    Alarm alarm = optionalAlarm.get();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = frostmourneTransactionManager.getTransaction(def);
    try {
        alarmRepository.deleteByPrimaryKey(alarmId);
        alertRepository.deleteByAlarm(alarmId);
        metricRepository.deleteByAlarm(alarmId);
        ruleRepository.deleteByAlarm(alarmId);
        rulePropertyRepository.deleteByAlarm(alarmId);
        recipientRepository.deleteByAlarm(alarmId);
        scheduleService.removeJob(Math.toIntExact(alarm.getJobId()));
    } catch (Exception ex) {
        frostmourneTransactionManager.rollback(status);
    }
    frostmourneTransactionManager.commit(status);
    return true;
}

11 View Source File : TransactionManager.java
License : Apache License 2.0
Project Creator : byteblogs168

public static TransactionInterceptor txAdvice(PlatformTransactionManager transactionManager) {
    // 只读事务,不做更新操作
    RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
    readOnlyTx.setReadOnly(true);
    readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    // 当前存在事务就使用当前事务,当前不存在事务就创建一个新事务
    RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
    requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    requiredTx.setTimeout(Constants.TX_METHOD_TIMEOUT);
    Map<String, TransactionAttribute> txMap = new HashMap<>(20);
    txMap.put("save*", requiredTx);
    txMap.put("add*", requiredTx);
    txMap.put("register*", requiredTx);
    txMap.put("create*", requiredTx);
    txMap.put("update*", requiredTx);
    txMap.put("remove*", requiredTx);
    txMap.put("delete*", requiredTx);
    txMap.put("cancel*", requiredTx);
    txMap.put("do*", requiredTx);
    txMap.put("get*", readOnlyTx);
    txMap.put("list*", readOnlyTx);
    txMap.put("page*", readOnlyTx);
    txMap.put("find*", readOnlyTx);
    txMap.put("search*", readOnlyTx);
    txMap.put("load*", readOnlyTx);
    txMap.put("*", readOnlyTx);
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    source.setNameMap(txMap);
    return new TransactionInterceptor(transactionManager, source);
}

10 View Source File : PostgresDatabaseInitializer.java
License : MIT License
Project Creator : yoomoney-tech

public static synchronized void initialize() {
    if (pgJdbcTemplate != null) {
        return;
    }
    String ryukImage = Optional.ofNullable(System.getProperty("testcontainers.ryuk.container.image")).orElse("quay.io/testcontainers/ryuk:0.2.3");
    TestcontainersConfiguration.getInstance().updateGlobalConfig("ryuk.container.image", ryukImage);
    String postgresImage = Optional.ofNullable(System.getProperty("testcontainers.postgresql.container.image")).orElse("postgres:9.5");
    PostgreSQLContainer<?> dbContainer = new PostgreSQLContainer<>(postgresImage);
    dbContainer.withEnv("POSTGRES_INITDB_ARGS", "--nosync");
    dbContainer.withCommand("postgres -c fsync=off -c full_page_writes=off -c synchronous_commit=off");
    dbContainer.start();
    PGSimpleDataSource dataSource = new PGSimpleDataSource();
    dataSource.setUrl(dbContainer.getJdbcUrl());
    dataSource.setPreplacedword(dbContainer.getPreplacedword());
    dataSource.setUser(dbContainer.getUsername());
    pgJdbcTemplate = new JdbcTemplate(dataSource);
    pgTransactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    pgTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    pgTransactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    executeDdl("CREATE SEQUENCE tasks_seq START 1");
    createTable(PG_DEFAULT_WO_INC_TABLE_DDL, DEFAULT_TABLE_NAME_WO_INC);
    createTable(PG_DEFAULT_TABLE_DDL, DEFAULT_TABLE_NAME);
    createTable(PG_CUSTOM_TABLE_DDL, CUSTOM_TABLE_NAME);
}

See More Examples