JPA多线程添加(如果不存在)? [英] JPA multithreaded Add if Not Exist?

查看:464
本文介绍了JPA多线程添加(如果不存在)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器功能,很多客户端都在同一时间多次调用它.服务器功能执行以下操作:

I have a server function which is called by many clients, many times exactly at the same time. The server function does the following:

  • 从客户端获取param1
  • 创建对象x(新对象x(param1))
  • 检查对象x是否存在于数据库中(jpa选择查询)
  • 如果不存在,则添加对象x(jpa商店实体)
  • 添加y(jpa商店实体)

当两个或多个客户端同时运行该函数,并且多个x对象被添加到数据库中时,这是错误的.

This goes wrong when two or more clients run the function at the same time, multiple x objects get added to the database.

我只是通过使用执行上述操作的同步方法创建单例管理器类来解决此问题.

I simply solved this by creating a singleton manager class with a synchronized method which does the above.

效果很好,因为现在该功能一次只能由一个客户端调用. (但是当有2台服务器时,我确实遇到了问题,但事实并非如此)

Works nicely, cause now the function can only be called by one client at a time. (but i do get a problem when there are 2 servers, but that isn't the case yet)

但是我想知道是否有更好的方法用jpa解决此问题?

But i was wondering is there a better way to solve this problem with jpa?

推荐答案

是的,整个操作应在事务内执行,例如JTA或Spring的@Transactional提供的事务.如果事务被隔离在适当的级别(在这种情况下,我认为是REPEATABLE_READ),则基础持久性系统将通过阻止一个事务直到另一个事务完成(基本上是synchronized)来确保不会发生冲突写入. ),或者在检测到冲突时停止并回滚第二个事务(然后可以重试).

Yes, this whole operation should be executed inside a transaction, such as provided by JTA or Spring's @Transactional. If the transaction is isolated at the proper level (I think REPEATABLE_READ for this case), the underlying persistence system will ensure that colliding writes don't occur, either by blocking one transaction until the other is complete (essentially what synchronized does in Java), or by stopping and rolling back the second transaction when it detects the conflict (which you can then retry).

这篇关于JPA多线程添加(如果不存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆