Spring Boot数据JPA在插入完成之前从数据库读取

huangapple 未分类评论50阅读模式
英文:

Spring-boot data jpa reads from the database before inserts get completed

问题

    @Transactional
    public void save(String myIds) 
    {
        synchronized (this) 
        {
            List<mydata> data = getDataToSaveOrUpdate(myIds); // 返回新的数据列表并更新旧数据
            repository.saveAll(data);
            logger.info("请求已处理");
        }
        logger.debug("方法退出");
    }

当这个方法在两个不同的 Postman 请求中被调用时,同步块会完成,但插入操作仍在进行中,第二个请求开始从数据库中读取数据。因此,第二个线程在两个请求中都找到相同的数据并尝试插入,导致唯一键冲突错误。在 Spring Boot 数据 JPA Hibernate 中,我们应该如何解决这个问题?

英文:
@Transactional
    public void save(String myIds) 
	{
            synchronized (this) 
			{
                List&lt;mydata&gt; data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info(&quot;request processed&quot;);
            }
        logger.debug(&quot;exiting the method&quot;);
    }

When this method is called in two separate request from postman what happens synchronized block gets completed but inserts are going and second request start reading from the data base .So second thread founds same data to insert in both the request and give unique key violation error how should we resolve this problem in springboot data jpa hibernate

huangapple
  • 本文由 发表于 2020年5月30日 02:40:05
  • 转载请务必保留本文链接:https://java.coder-hub.com/62092668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定