java多线程里能使用mybatis或者jpa插入吗?

发布于 2022-09-11 22:51:02 字数 1207 浏览 16 评论 0

//下面是按照老大Richard_Yi的法子做出来的,截图如下
2019-10-10_060932.png

/////////////下面是旧的
2019-10-10_060932.png

//最新更新,截图如上,项目结构能够看见,说下,我那个brandRepository在别的包可以插入的,比如controller里的方法,就是在这个包下不行,不是一直都插入不进去的

public class ThirdThread implements Runnable {

private Brand brand;
private BrandRepository brandRepos;
@Autowired
BrandRepository brandRepository;
Logger logger = LoggerFactory.getLogger(getClass());
public ThirdThread() {
    this.brandRepos=brandRepository;
    this.brand = new Brand();    }
@Override
public void run() {
    logger.info("third开始时间"+System.currentTimeMillis());
    for (int i = 1; i < 11; i++) {
        brand.setId(i);
        brand.setName("wygyf");
        brand.setFirstname("gheu");
        brand.setCid(1);
        brandRepos.save(brand);
    }
    //上面是线程类的代码,然后到调用的地方
    
            Thread thread = new Thread(new ThirdThread());
    thread.start();
    
    
    
    代码如上,现在的问题是,每次还是报空指针,就是save那,我问人说是因为异步线程,来不及注入所以一直为空,我在构造函数里将bean注入了,但jpa那怎么操作我不知道。
    
    求高人解惑,谢谢

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

oО清风挽发oО 2022-09-18 22:51:02

题主的目的:一个线程插入大批量的数据,和多个线程同时插入大批量的数据,在时间上是否有差距,所以在线程里用正常的orm方式操作数据库;
他想用Spring-Data-Jpa这种方式去插入数据,简化操作。

看着像SpringBoot应用。举个例子

@AllArgsConstructor
public class Task implements Callable<String> {

    private String name;

    private BrandRepository brandRepository;

    @Override
    public String call() throws Exception {
        long temp = System.currentTimeMillis();
        for (int i = 1; i < 10; i++) {
            brandRepository.save(new Brand(name, i));
        }
        return name + "执行耗时" + (System.currentTimeMillis() - temp);
    }
}

BrandRepository

@Data
@ToString
@NoArgsConstructor
 @AllArgsConstructor
public class Brand {

    private String name;
    private int seq;
}


/**
 * @author Richard_yyf
 * @version 1.0 2019/10/11
 */
// 把这个 Component 类比 Repository
@Component
public class BrandRepository {

    public void save(Brand brand) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行插入数据库操作 " + brand.toString());
    }
}

main方法

@SpringBootApplication
@Slf4j
public class Demo999Application {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Demo999Application.class, args);
        //System.in.read(); // press any key to exit

        ExecutorService executor = Executors.newCachedThreadPool();
        try {
            List<Callable<String>> list = new ArrayList<>();
            list.add(new Task("线程1", context.getBean(BrandRepository.class)));
            list.add(new Task("线程2", context.getBean(BrandRepository.class)));
            List<Future<String>> futures = executor.invokeAll(list);
            for (Future<String> future : futures) {
                System.out.println("任务执行完成:" + future.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            log.error("", e);
        }
        try {
            executor.shutdown();

            if(!executor.awaitTermination(10000, TimeUnit.MILLISECONDS)){
                // 超时的时候向线程池中所有的线程发出中断(interrupted)。
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // awaitTermination方法被中断的时候也中止线程池中全部的线程的执行。
            System.out.println("awaitTermination interrupted: " + e);
            executor.shutdownNow();
        }
    }

}

如果是Spring的话同理,用个java configuration类配置或者扫描相关的Bean,然后main方法里用new ***ApplicationContext()启动容器,如上操作即可。

执手闯天涯 2022-09-18 22:51:02
  1. 空指针说明没有注入,是根本没有注入,不是没来得及注入
蓝礼 2022-09-18 22:51:02

都可以用MyBatis或者jpa写入数据库。看到你的代码,我猜测是两个原因,一是根本没有这个接口,而是@AutoWired的问题。
首先着重讲一下@AutoWired的问题,@AutoWired我觉得它的使用场景比较少,多用于只有一个实现类的接口,我曾经也遇到@AutoWired空指针的问题,我自己是改用@Resource的注解。
另外你通过注入,然后再通过构造器赋值,这一步我没看懂原因,直接@Resource或者用@AutoWired以及@Qualifier组合注入就可以了。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文