java 读取时休眠行锁定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17757732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:53:03  来源:igfitidea点击:

Hibernate Row Locking on read

javaspringhibernatetomcattransactions

提问by James

I have a table Jobswith fields Nameand Status.

我有一个Jobs包含字段NameStatus.

I'm trying to deploy two separate applications in a tomcat instance to poll the jobs table for new records but it's important that the same job record is not received by both processes. How can I do this?

我正在尝试在 tomcat 实例中部署两个单独的应用程序以轮询作业表以获取新记录,但重要的是两个进程都不会收到相同的作业记录。我怎样才能做到这一点?

My (unsuccessful) approach thus far has been to use spring integration:

到目前为止,我的(不成功的)方法是使用 spring 集成:

<int-jdbc:inbound-channel-adapter 
    query="select * from jobs where status=1"
    channel="rawInputDataListChannel"
    data-source="dataSource"
    update="update input_table set status=2 where status=1">
    <int:poller fixed-rate="1">
        <int:transactional isolation="READ_COMMITTED" />
    </int:poller>
</int-jdbc:inbound-channel-adapter>

Since this didn't work I thought that maybe having the transaction manager in tomcat so it could be shared by both applications might work but I'm struggling to get that up and running. Would this approach work?

由于这不起作用,我认为可能在 tomcat 中有事务管理器以便两个应用程序共享它可能会起作用,但我正在努力使其启动和运行。这种方法行得通吗?

回答by incomplete-co.de

the title of your question mentions hibernate so lets look at what JPA 2.0 has to offer which is around the idea of LockModeand pessimistic locking. in the case you're looking at, you want to run queries, possibly simultaneously, and have each JVM get a unique set of results. that being the case, you want to emulate a SELECT... FOR UPDATE(which is kinda proprietary and dependant on your database as to whether or not it will directly support that statement).

你的问题的标题提到了休眠,所以让我们看看 JPA 2.0 必须提供什么,它围绕着LockMode悲观锁定的想法。在您查看的情况下,您希望运行查询,可能同时运行,并让每个 JVM 获得一组唯一的结果。在这种情况下,您想要模拟 a SELECT... FOR UPDATE(这有点专有并且取决于您的数据库是否会直接支持该语句)。

in JPA 2.0 you can use @LockModeand specify that the resultset is retrieve with the intention of updating, so 'lock' it at the database so no other connection can get the same results.

在 JPA 2.0 中,您可以使用@LockMode并指定检索结果集以进行更新,因此将其“锁定”在数据库中,以便其他连接无法获得相同的结果。

have a look at thisarticle to try and explain it better than i, and have a look particularly at the 'pessimistic' patterns.

看看这篇文章,尝试比我更好地解释它,特别是看看“悲观”模式。

edit >>>

编辑 >>>

if you're looking at hibernate 3.x, try thislink

如果您正在查看 hibernate 3.x,请尝试链接