Search code examples
nhibernatenamed-querynhibernate-mapping-by-code

How to map a sql function as named query with Nhibernate's loquacious mapping?


I have replaced all my NHibernate xml mapping files by loquacious mappings (mapping by code). The only thing I can't figure out is if it is possible to define this named query using loquacious mappings:

<?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>

Does anyone know if it's possible, and so how to do it or point me in the right direction?

Thanks in advance, Regards, Ted


Solution

  • You can still mix your mappings, that is use all the new juiciness of mapping by code and still have some of your HBM named mapping files.

    The solution is quite simple, first you need to define your web.config (or external nhibernate config file) as:-

    <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> 
    

    Then configure NHibernate accordingly:-

    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();
    

    I have written a blog post regarding this.