按请求变量事务隔离级别 [英] Variable transaction isolation levels by request

查看:138
本文介绍了按请求变量事务隔离级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写一个小型拍卖应用程序,我的出价肯定会被记录下来非常重要。毕竟,拍卖的最后几秒是买家的关键时刻,我不能冒险同时竞标和竞争条件。

I am writing a little auction app, and it is very important that my bids are recorded with certainty. After all, the last couple seconds of the auction are critical moments for the buyers, and I can't risk them simultaneously bidding and having a race condition.

当然这就是事务隔离的目的。我可以将我的隔离级别设置为可序列化,我们都已设置好。

And of course, that's what transaction isolation is for. I can set my isolation level to serializeable, and we're all set.

但是所有其他请求呢?如果人们正在查看配置文件或发送消息,则这些请求不需要接近那种事务隔离。读取提交的隔离级别对于这些请求是完全可以接受的。

But what about all the other requests? If people are viewing profiles, or sending messages, these requests don't need anywhere near that kind of transaction isolation. A read committed isolation level is perfectly acceptable for those requests.

我将我的事务级别设置为我的hibernate属性 hibernate.connection的一部分。隔离,但我真的希望能够为每个请求执行类似 session.setTransactionIsolation(newIsolation)的操作。

I'm setting my transaction level as part of my hibernate property hibernate.connection.isolation, but I'd really like to be able to do something like session.setTransactionIsolation(newIsolation) per request.

推荐答案

Session session = getSession(dataSource, sessionFactory, Connection.TRANSACTION_SERIALIZABLE);

public Session getSession(DataSource dataSource, SessionFactory sessionFactory, int isolationLevel){

  // Get connection from current dataSource and set new isolation
  Connection connectionWithNewIsolation = dataSource.getConnection();
  connectionWithNewIsolation.setTransactionIsolation(isolationLevel);

  // Get session from current sessionFactory with the new isolation
  Session session = sessionFactory.openSession(connectionWithNewIsolation);

  // Hibernate 4.3
  //SessionFactory.openStatelessSession(Connection connection)
  // Hibernate 3.6
  //SessionFactory.openSession(Connection connection)
  //SessionFactory.openStatelessSession(Connection connection)

  return session;
}

这篇关于按请求变量事务隔离级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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