使用 nolock 的 Java Hibernate HQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3500106/
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
Java Hibernate HQL queries with nolock
提问by Sarit
Is there a way to run these queries as if I added a (NOLOCK) hint to them?
有没有办法运行这些查询,就好像我向它们添加了(NOLOCK)提示一样?
采纳答案by GaryF
If you really need this, then you want to do something like:
如果你真的需要这个,那么你想做这样的事情:
session.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
which is identical to a nolock.
这与 nolock 相同。
Before you do that, really think carefully if you want to do a dirty read. Most of the time people do this because it's what they've always done, rather than because it's the right thing to do. In particular, this does not work well with caching.
在您这样做之前,如果您想进行脏读,请务必仔细考虑。大多数时候人们这样做是因为这是他们一直在做的事情,而不是因为这是正确的做法。特别是,这不适用于缓存。
Actually, this threadgoes into the issues a little. Read carefully before deciding.
实际上,这个线程涉及到一些问题。在决定之前仔细阅读。
回答by mkbrv
In latest version of Hibernate you have to do it this way:
在最新版本的 Hibernate 中,您必须这样做:
Session session = (Session) em.getDelegate();
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
}
});
回答by Larry
You can do the "with (nolock)" if you go native. This is extreme but if the alternative is changing the transaction isolation level, you might rather do this.
如果你是本地人,你可以做“with (nolock)”。这是极端的,但如果替代方案是更改事务隔离级别,您可能更愿意这样做。
Note that this example is for MSSQL.
请注意,此示例适用于 MSSQL。
String sqlQueryString = "SELECT * FROM my_classes_table WITH (nolock) WHERE columnName = :columnValue";
SQLQuery sqlQuery= session.createSQLQuery(sqlQueryString).addEntity(MyClass.class);
sqlQuery.setLong("columnValue", value);
List<MyClass> out = sqlQuery.list();

