代码之家  ›  专栏  ›  技术社区  ›  Mike Sickler

我可以用nHibernate自定义查询结果的排序规则吗?

  •  6
  • Mike Sickler  · 技术社区  · 14 年前

    在普通的旧SQL中,我可以这样做:

    select * from mytable COLLATE Latin1_General_CS_AS

    有没有办法在nHibernate、HQL或criteria中指定要用于给定查询的排序规则类型?

    2 回复  |  直到 14 年前
        1
  •  6
  •   rebelliard    14 年前

    Germn Schuager已设法在运行时指定排序规则。看一看 here .

    var user = session.CreateCriteria(typeof (User))
        .Add(Expression.Sql("Username like ? collate Modern_Spanish_CS_AS", username, NHibernateUtil.String))
        .UniqueResult<User>();
    
        2
  •  2
  •   Community CDub    8 年前

    same link rebelliard answer 提供,Shuager还提供了一种定义自定义函数以执行类似操作的方法。这在HQL中也有可用的优势。

    他的自定义函数实现对于您的问题和我自己的需要来说太具体了,所以这里是我结束的实现:

    /// <summary>
    /// Customized dialect for allowing changing collation on <c>like</c> statements.
    /// </summary>
    public class CustomMsSqlDialect : MsSql2008Dialect
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public CustomMsSqlDialect()
        {
            RegisterFunction("withcollation",
                new WithCollationFunction());
        }
    }
    
    /// <summary>
    /// Add collation to string argument.
    /// </summary>
    [Serializable]
    public class WithCollationFunction : SQLFunctionTemplate, IFunctionGrammar
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WithCollationFunction()
            : base(NHibernateUtil.String, "?1 collate ?2")
        {
        }
    
        bool IFunctionGrammar.IsSeparator(string token)
        {
            return false;
        }
    
        bool IFunctionGrammar.IsKnownArgument(string token)
        {
            return Regex.IsMatch(token, "[A-Z][A-Z0-9_]+_(?:CS|CI)_(?:AS|AI)(?:_KS)?(?:_WS)?", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
        }
    }
    

    注意方言基类,我用了2008年的方言,你不妨改一下。 不要忘记将HQL方言更改为新的自定义方言(例如,使用会话工厂的“方言”配置属性)。

    HQL中的示例用法,不带排序规则自定义的标准查询:

    from Cat as c
    where c.Name like 'fel%'
    

    使用自定义排序规则

    from Cat as c
    where c.Name like withCollation('fel%', French_CI_AI)
    

    与Nhib 3.2合作。