【问题标题】:How to map a sql function as named query with Nhibernate's loquacious mapping?如何使用 Nhibernate 的 loquacious 映射将 sql 函数映射为命名查询?
【发布时间】:2011-12-16 09:52:28
【问题描述】:

我已将我所有的 NHibernate xml 映射文件替换为 loquacious 映射(按代码映射)。我唯一想不通的是是否可以使用 loquacious 映射来定义这个命名查询:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping namespace="Domain" assembly="Domain" xmlns="urn:nhibernate-mapping-2.2"> 
  <sql-query name="MyFunction">
    <query-param name="Inputparam1" type="Int32"/>
    <query-param name="Inputparam2" type="Int32"/>
    <return-scalar column="ResultParam" type="Int32"/>
    <![CDATA[ select MyFunction(:Inputparam1,:Inputparam2) as ResultParam ]]>
  </sql-query>
</hibernate-mapping>

有谁知道这是否可能,以及如何做到这一点或为我指明正确的方向?

提前致谢, 问候,泰德

【问题讨论】:

    标签: nhibernate named-query mapping-by-code


    【解决方案1】:

    您仍然可以混合您的映射,即使用代码映射的所有新功能,并且仍然有一些 HBM 命名的映射文件。

    解决方案很简单,首先你需要将你的 web.config(或外部 nhibernate 配置文件)定义为:-

    <configSections>  
      <section name="hibernate-configuration"  
       type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
         requirePermission="false" />  
    </configSections>  
    
    <hibernate-configuration  
       xmlns="urn:nhibernate-configuration-2.2">  
      <session-factory>  
        <property name="dialect">  
          NHibernate.Dialect.MySQL5Dialect  
        </property>  
        <mapping assembly="Domain.Model" />  
      </session-factory>  
    </hibernate-configuration> 
    

    然后相应地配置NHibernate:-

    var mapper = new ModelMapper();
    mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
    //Notice the .Configure, this is the magic that allows you to
    //  use the mixed mappings
    var configure = new Configuration().Configure();
    configure.DataBaseIntegration(x =>
    {
      x.Dialect<MySQL5Dialect>();
      x.ConnectionStringName = "db";
    }).CurrentSessionContext<WebSessionContext>();
    
    configure.AddDeserializedMapping(mapping, "Domain");
    SessionFactory = configure.BuildSessionFactory();
    

    我已经为此写了blog post

    【讨论】:

    • 嗨 Rippo,很抱歉我忘了提,但这正是我现在所拥有的。我只是想知道我是否可以完全丢失 xml 文件。顺便说一句:因为你的博客,我得到了这个!几周前就已经找到了。谢谢你的博客!
    • 如果您确实找到了解决方案,您会在此处发布吗?我自己还没有解决这个问题
    • 我会的。过去一年我学到了很多关于 NHibernate 的知识。
    • 我拥有的命名查询是 xml 格式中唯一剩下的东西,我决定在会话上使用 CreateSqlQuery 执行它。它并不比使用 XML 更容易出错,两者都可以包含拼写错误。我用一些单元测试覆盖了它。这样我就摆脱了 xml 映射配置。
    猜你喜欢
    • 2013-01-04
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多