Halaman

Jumat, 24 September 2010

Fluent NHibernate with MySQL

NHibernate is an Object Relational Mapping framework, which (as ORM states) maps between relational data and objects. It defines its mappings in an XML format called HBM, each class has a corresponding HBM XML file that maps it to a particular structure in the database.

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents (.hbm.xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code. Fluent, XML-less, compile safe, automated, convention-based mappings for NHibernate.

Fluent NHibernate is external to the NHibernate Core, but is fully compatible with NHibernate version 2.1, and is experimentally compatible with NHibernate trunk.

Why replace HBM.XML? While the separation of code and XML is nice, it can lead to several undesirable situations.

  • Due to XML not being evaluated by the compiler, you can rename properties in your classes that aren't updated in your mappings.
  • XML is verbose; NHibernate has gradually reduced the mandatory XML elements, but you still can't escape the verbosity of XML.
  • Repetitive mappings - NHibernate HBM mappings can become quite verbose if you find yourself specifying the same rules over again. For example if you need to ensure all string properties mustn't be nullable and should have a length of 1000, and all ints must have a default value of -1.

To counter these issues Fluent NHibernate does by moving mappings into actual code, so they're compiled along with the rest of your application; rename refactorings will alter your mappings just like they should, and the compiler will fail on any typos. As for the repetition, Fluent NHibernate has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things; you set how things should be named once, then Fluent NHibernate does the rest.

My post before, shows an example of using NHibernate. Below we modify the previous code to work with Fluent NHibernate.

  1. Download fluentnhibernate-1.1.zip then extract.
  2. Create a console application using Visual Studio and named as FluentNHibernateSample.
  3. Add reference to FluentNHibernate.dll, NHibernate.ByteCode.Castle.dll, NHibernate.dll. In this sample we work with MySQL, so add MySql.Data.dll and remember to set Copy Local property to true.
  4. Here the modified version of my previous code:

using System;
using System.Collections.Generic;
using System.Collections;
using MySql.Data.MySqlClient;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using System.Linq;
using FluentNHibernate.Mapping;

namespace FluentNHibernateSample
{
class Program
{
static void Main(string[] args)
{
FluentConfiguration config = Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString(c => c
.Server("localhost")
.Database("mydb")
.Username("myname")
.Password("mypass")));
ISessionFactory factory = config.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Coba>())
.BuildSessionFactory();

var session = factory.OpenSession();
System.Collections.IList myRows = session.CreateCriteria(typeof(Coba)).List();
foreach (Coba item in myRows)
Console.WriteLine("Id:{0} - Ket:{1}", item.Id, item.Ket);

IQuery query = session.CreateQuery("from Coba order by ket desc");
IList<Coba> dta = query.List<Coba>();
foreach (Coba item in dta)
Console.WriteLine("Id:{0} - Ket:{1}", item.Id, item.Ket);

query = session.CreateQuery("FROM Coba WHERE kode=:kode");
query.SetString("kode", "19");
foreach (Coba item in query.List<Coba>())
Console.WriteLine("\nResult:\nID:{0} with Ket:{1}", item.Id, item.Ket);
session.close();
Console.ReadKey();
}
}
public class Coba
{
public virtual string Id{ get; private set; }
public virtual string Ket {get; set;}
}

public class CobaMap : ClassMap<Coba>
{
public CobaMap()
{
Table("masjob");
Id(x => x.Id).Column("kode");
Map(x => x.Ket, "ket");
}
}
}

  1. Run. We get the same result with my previous code.


The code does not use xml configuration files at all!

10 komentar:

  1. what has this to do with MySQL??? could have been any database

    BalasHapus
  2. Thank you, good example.

    BalasHapus
  3. how do i get the sql file and how do i export to hbm files? can i do this when i do the testing?

    I want to create the database before i do my web project.

    BalasHapus
  4. My coder is trying to persuade me to move to .

    net from PHP. I have always disliked the idea because
    of the expenses. But he's tryiong none the less. I've been using
    Movable-type on numerous websites for about a
    year and am concerned about switching to another platform.
    I have heard excellent things about blogengine.net. Is there a
    way I can transfer all my wordpress posts into it?

    Any help would be really appreciated!

    Feel free to visit my site; upper back pressure after eating

    BalasHapus
  5. This is a topic that is close to my heart..

    . Cheers! Exactly where are your contact details though?


    Here is my website; las vegas golf schools

    BalasHapus
  6. Hi there! This blog post could not be written much better!
    Going through this article reminds me of my previous roommate!
    He constantly kept preaching about this. I'll send this article to him. Fairly certain he'll have a good read.
    Thank you for sharing!

    Here is my web-site; personal injury attorney

    BalasHapus
  7. Hello! I just wanted to ask if you ever have any problems with hackers?
    My last blog (wordpress) was hacked and I ended up
    losing many months of hard work due to no backup. Do you have any solutions to prevent
    hackers?

    Here is my web blog - pinched nerve in neck

    BalasHapus
  8. I'm gone to tell my little brother, that he should also visit this web site on regular basis to obtain updated from most recent reports.

    Feel free to surf to my blog neck stretches for headaches (Www.2findlocal.com)

    BalasHapus
  9. Excellent goods from you, man. I've understand your stuff previous to and you are just extremely fantastic. I really like what you've acquired here, certainly like what you're saying and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I can not wait to read much more from you. This is really a wonderful site.

    Here is my web page - pittsburgh florists sunday delivery

    BalasHapus
  10. No matter if some one searches for his essential thing,
    so he/she desires to be available that in detail, so that thing
    is maintained over here.

    My webpage - low income counseling services

    BalasHapus