首页 > 解决方案 > hibernate查询中使用nolock时出现识别错误

问题描述

我有简单的休眠查询,查询中使用了 nolock。我收到错误 - 发生识别错误并且休眠错误是抛出异常:NHibernate.dll 中的“NHibernate.Hql.Ast.ANTLR.QuerySyntaxException”。它可以在没有锁定的情况下工作。我不想用

<property name="connection.isolation">ReadUncommitted</property>

因为我必须仅将 nolock 应用于特定表。

以下是 hql 查询 -

select d from Users d with (nolock) where d.Userid = 2 

我错过了什么吗?

标签: c#sqlsql-servernhibernateread-uncommitted

解决方案


HQL 将不支持直接with (nolock). 但是我们可以使用原生 SQL 查询。

因此,例如,而不是这样的(获取用户列表):

var hql    = "select d from Users d with (nolock) where d.Userid = 2";
var query  = session.CreateQuery(sql);
var result = query.List<User>();

我们需要使用原始 sql API

var sql    = "select d.* from schema.UserTable d with (nolock) where d.user_id = 2 ";
var query  = session.CreateSQLQuery(sql);
var result = query
    .AddEntity(typeof(User))
    .List<User>();

如果我们知道通过 ID 只会返回一个用户.. 我们可以使用UniqueResult<>而不是List


推荐阅读