Anda di halaman 1dari 11

Introduction to NHibernate

By: Jojo Sardez (Apr 25, 2011) NHibernate is an open source ORM tool for .Net framework based applications. Its design and concept is based on the Hibernate ORM for Java. The tool really helps developers to work fast since it gives us more time to write codes and less time minding the database management stuff since NHibernate does the database CRUD operations for us. All we need to do is set up the mappings, repositories, and configurations and were ready to communicate with the database. To benefit to this technology, you must first download the binaries at the NHibernate website (Download the binaries, not the Alpha). To see how NHibernate works, we are going to make a simple application showcasing it. Note: All names, solution and project structures are for demo purposes only and might not be the best structure you will encounter. You can design your own structure and naming conventions when writing your own NHibernate application or depends on your institution \ companys coding standards .Also on NHibernate, segregating objects by their use and type per project is highly observed. The Next steps will demonstrate this practice. 1. Create a solution named MyFirstNHibernateApp. 2. Next we need to create a project that will contain the model or structure of our databases tables. 2.1. Create a Class Library project named MyFirstNHibernateApp.Model. 2.2. Now we need to create our object. Create a class named Item. 2.2.1. Define the following properties inside the class: public virtual int? ItemId { get; set; public virtual string ItemName { get; set; } The object and properties youve defined will represent the Table and its Fields during runtime. Take note that the properties need to be declared as public virtual or NHibernate will not be able to map it. At the end of this step your Solution Explorer should look like this:

Figure 1: MyFirstNhibernateApp solution containing MyFirstNhibernateApp.Model project.

3. Next we need to create a Class Library project that will contain our interface for the Repository a common interface that contains CRUD and advance data access operations that Repositories should should implement. You will learn more about Repositories on Step 4. 3.1. Create a Class Library project named MyFirstNHibernateApp.Repository. 3.2. Create an interface named IRepository which uses Generics to define object of class and the objects key type. Define the interface with 3 methods as follows: public interface IRepository<TD, TK> where TD : class { TD GetById(TK id); void Save(TD saveObj); void Delete(TD delObj); } At the end of this step your solution explorer should look like this:

Figure 2: MyFirstNhibernateApp solution containing the Model and Repository projects.

4. Now we need to create a Class Library project that will hold our XML mappings and Repository implementation. 4.1. Create a Class Library project named MyFirstNHibernateApp.Data. 4.2. Add a Project Reference for the 2 two projects weve done earlier. 4.3. Add a File Reference to the assembly NHibernate.dll You can find it at the Required_Bins directory when you extract the NHibernate libraries you downloaded. 4.4. For the XML mappings, 4.4.1. Create a folder named Mappings. 4.4.2. Inside the folder, create a XML file named Item.hbm.xml (The files extension is required by NHibernate to be .hbm.xml). On the files property set its Build Action to Embedded Resource for NHibernate to be able to read it. Write the following on the file: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly=" MyFirstNHibernateApp.Model" namespace=" MyFirstNHibernateApp.Model"> <class name="Item" table="Items"> <id name="ItemId"> <generator class="identity" /> </id> <property name ="ItemName" length="50" /> </class> </hibernate-mapping> Here are some of the details defined on the XML file: assembly defines the assembly name that contains the model that the current XML mapping file represents. namespace defines the namespace on the assembly name that contains the model that the current XML mapping file represents. class contains information about the class \ model. name the name of the class \ model that the current XML mapping file represents. table the table name on the SQL Server database that the class \ model represents. id represents a primary key field. property represents a normal table field. 4.5. For the Session Provider (Class that accesses NHibernates ISessionFactory object the object that initializes database connection, creates session for transactional operations, etc.), 4.5.1. Create a folder named SessionProviders 4.5.2. Create a class named SessionProvider and design it as follows: public class SessionProvider { private static ISessionFactory _sessionFactory; private static Configuration _configuration; public static ISessionFactory SessionFactory

get {

} }

if (_sessionFactory == null) _sessionFactory = CreateSessionFactory(); return _sessionFactory;

public static Configuration Config { get { if (_configuration == null) { _configuration = new Configuration(); _configuration.AddAssembly(System.R eflection.Assembly.GetCallingAssembly()); } return _configuration; } } private static ISessionFactory CreateSessionFactory() { return Config.BuildSessionFactory(); } public static void RebuildSchema() { var schema = new SchemaExport(Config); schema.Create(true, true); } } 4.6. Next is for repository implementations. Repositories are objects that implemented the IRepository interface. These objects contain the basic and even complex CRUD operations for specific model thus means you should provide Repository for each model youre working into. Repositories make use of the SessionProvider \ ISessionFactory to establish database connection and other relational database tasks. 4.6.1. Create a folder named Repositories. 4.6.2. Create a class named ItemRepository. 4.6.3. Add the following code before the class namespace declaration: using MyFirstNHibernateApp.Data.SessionProviders; using MyFirstNHibernateApp.Model; using MyFirstNHibernateApp.Repository; 4.6.4. Design the class as follows: public class ItemRepository : IRepository<Item, int?>

#region IRepository<Item,int?> Members public Item GetById(int? id) { using (var session = SessionProvider.SessionFactory.OpenSession()) { return session.Get<Item>(id); } } public void Save(Item info) { using (var session = SessionProvider.SessionFactory.OpenSession()) { using (var trans = session.BeginTransaction()) { session.SaveOrUpdate(info); trans.Commit(); } } } public void Delete(Item info) { using (var session = SessionProvider.SessionFactory.OpenSession()) { using (var trans = session.BeginTransaction()) { session.Delete(info); trans.Commit(); } } }

#endregion

Your Solution Explorer should now look like this:

Figure 3: MyFirstNhibernateApp solution containing the Model, Repository, and Data projects.

5. Now to see it work we need a client application. 5.1. Create a Console Application named MyFirstNHibernateApp.Console. 5.2. Set is as the solutions StartUp project. 5.3. Add reference to MyFirstNHibernateApp.Data, MyFirstNHibernateApp.Model, and MyFirstNHibernateApp.Repository projects. 5.4. Add reference to NHibernate.dll assembly. 5.5. Add reference to the assembly NHibernate.ByteCode.Castle.dll You can find it at the Required_For_LazyLoading\Castle directory when you extract the NHibernate libraries you downloaded. 5.6. Add an Application Configuration file containing this elements: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" requirePermission="false"

type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> </configSections> <hibernate-configuration xmlns="urn:nhibernateconfiguration-2.2"> <reflection-optimizer use="false" /> <session-factory> <property name="connection.provider">NHibernate.Connecti on.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.MsSql2005Dia lect</property> <property name="connection.driver_class">NHibernate.Driv er.SqlClientDriver</property> <property name="connection.connection_string">Data Source=(local); Initial Catalog=MyFirstNHibernateDB; Trusted_Connection=true;</property> <property name='proxyfactory.factory_class'>NHibernate.B yteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration> </configuration> Change the connection string details to match your SQL Server database engine information. Also, the database name you specified on the connection string must be existing on the database server. Your Solution Explorer should now look like this:

Figure 4: MyFirstNhibernateApp solution containing all the 4 projects.

5.7. Let us now try persisting information to the database. 5.7.1. On Program.cs, add the following codes before the namespace declaration: using MyFirstNHibernateApp.Data.Repositories; using MyFirstNHibernateApp.Data.SessionProviders; using MyFirstNHibernateApp.Model; 5.7.2. Add the following code inside the static void Main(string[] args) method: SessionProvider.RebuildSchema(); ItemRepository repo = new ItemRepository(); var newItem = new Item { ItemName = "My item's name" }; repo.Save(newItem); Run the program by pressing F5. You will notice the following output on the console window:

Figure 5: Console Window showing NHibernate generated output.

When the first line is executed, NHibernate will automatically create tables of all mapped models to the database specified in the connection string (thats the reason theres a create table script printed on the console window). The tables will match the Model and Mappings defined on the previous projects. On the next line we created an instance of the ItemRepository which we need in persisting Item objects into the database. Then on the subsequent lines, we created an Item object, the one we will persist using the ItemRepositorys Save method last line. If you are going to look at the SQL Server Management Studio, you will see that the table Items was automatically created. The information we coded was also successfully persisted on it.

Figure 6: A query executed on Microsoft SQL Server Management Studio showing the created table and the persisted information into it.

5.8. Let us now try retrieving an object from the database, modify it, and save its updated values. 5.8.1. On Program.cs, add the following code inside the static void Main(string[] args) below the codes we added on step 5.7: var retrievedItem = repo.GetById(newItem.ItemId); retrievedItem.ItemName = "Modified item name"; repo.Save(retrievedItem); Run the program by pressing F5. You will notice that the code also called the Save method for saving modified information. It is because NHibernates Session Factorys SaveOrUpdate method automatically detects if the object youre trying to save is new or already exists. (by checking if the objects property that represents the ID has value or none) When you check on SQL Server Management Studio, you will see the objects ItemName field value is now Modified item name. You will also notice that there is just 1 record on the table and the one we created on Step 5.7 is gone. Is it because the SessionProvider.RebuildSchema() statement drops a table if it already exist and recreate it based on mapping and model details. You should be able to make good use of it when you create your actual applications.

Figure 7: A modified record.

5.9. Last we will try the delete operation. 5.9.1. Add this code before the method static void Main(string[] args) ends : repo.Delete(retrievedItem); Run the program by pressing F5. When you check on SQL Server Management Studio, you will see that there were no records on the table since NHibernate deleted the only one.

Figure 8: No records were found on the table.

Conclusion
We have discussed NHibernate and demonstrated its basic operations. On my next articles, I will try to cover NHibernates other features such as mapping related tables, using criteria, etc.

Anda mungkin juga menyukai