@Transactional 注解在多线程环境下不生效问题

@Transactional 注解在多线程环境下不生效问题

直接上代码

package com.linzi.risk.indicator.service.impl;

import com.linzi.risk.common.utils.threadpool.ThreadPoolManager;
import com.linzi.risk.indicator.dao.AsyncCommandDao;
import com.linzi.risk.indicator.entity.AsyncCommandEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * @author chentiefeng
 * @date 2018/10/11 14:47
 */
@Component
public class TestTrans {

    @Resource
    private AsyncCommandDao asyncCommandDao;

    @Transactional
    public void test() {
        AsyncCommandEntity command = new AsyncCommandEntity();
        command.setType("test");
        command.setBsnNo("1");
        command.setBsnType("1");
        command.setContent("");
        try {
            command.setAddIp(InetAddress.getLocalHost().getHostName());
            command.setUpdateIp(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        command.setAddTime(new Date());
        command.setUpdateTime(new Date());
        command.setState("INIT");
        asyncCommandDao.insert(command);
        TransactionAspectSupport.currentTransactionStatus().flush();
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                AsyncCommandEntity entity = asyncCommandDao.selectById(command.getId());
                System.out.println("Transactional 事务下异步线程查询:" + entity);
                if (entity.getId() != null) {
                    asyncCommandDao.delete(entity.getId());
                }
            }
        });
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

因为插入后睡眠了500毫秒,所以运行结果就是报空指针异常。
不了解的情况下以为TransactionAspectSupport.currentTransactionStatus().flush();方法能手动commit事务,原来不行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值