首页 > 解决方案 > 如何解决jpa存储库保存方法中的多线程

问题描述

我使用 spring data jpa 来保存实体。
我尝试在这里以不同的方式保存它。
我是多线程的,我运行 save() 方法,所以我注意到有些 save() 有效,但有些 save() 无效。

下面是我的代码。

private static final Executor EXECUTOR = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

/**
 * @param book
 */
@Transactional
public void multipleSave(final Book book) {
    IntStream.range(0, 2).forEach(index -> EXECUTOR.execute(() -> {
        log.info("(1) current thread name :: {}", Thread.currentThread().getName());
        Optional<Book> optional = bookJpaRepository.findById(book.getId());

        if(optional.isPresent()) {
            optional.get().update(book);
            return;
        }

        bookJpaRepository.save(book);
        log.info("(2) current thread name :: {}", Thread.currentThread().getName());
    }));
}

下面的错误信息

Exception in thread "pool-1-thread-38" org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [book.PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

...java

Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at  

....

Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '130' for key 'book.PRIMARY'

那么如何解决这个问题..?
给我任何意见,我会参考它。

谢谢。

标签: hibernatejpaspring-data-jpa

解决方案


推荐阅读