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

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

问题描述

我正在编写一个小拍卖应用程序,并且确定地记录我的出价非常重要.毕竟,拍卖的最后几秒对买家来说是关键时刻,我不能冒险让他们同时出价和竞争.

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.connection.isolation 的一部分,但我真的很希望能够执行类似 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天全站免登陆