And welcome back to part 2 of our newbie nhibernate tutorial series. Here is a quick summary of what we did the last time, in part 1:
- Create a basic database (w/ 1 table)
- Create a new console application
- Add the nhibernate binary files as references to our application
2.1 Creating the Entity Class
So far, so good. This time we will proceed with mapping our first table into a .NET class:
- Open the DevJour1 project we created the last time
- Add a new class to our project (right-click the project -> Add -> Class).
- Name it Book
- Add the properties as in the snippet below:
Figure 1: This class will reflect our table Book as of SQL Server DevJour database we created in part 1 of the tutorial series. Each field of the table Book will be mapped accordingly to the class’ property with the same name.
2.2 Creating the Mapping File
The mapping file is an XML document which tells nhibernate which DB field belongs to which property in the class, which type it has and many more things. Let’s dig right in:
1. Create and XML document (right-click on project -> Add new item -> XML file)
2. Name the XML file Book.hbm.xml and click on “Add” (Figure 2)
3. Important: Under Book.hbm.xml file’s properties, under Build Action, choose Embedded Resource. It will not work if you do not choose this type! (Figure 3)
4. Write the code for the mapping file according to Figure 4
Figure 2: Adding the mapping file. The .hbm. middle part of the file name stands for hibernate mapping.
Figure 3: Set the Build Action to Embedded Resource!
Figure 4: The mapping file Book.hbm.xml
2.3 Explanation of the Mapping File (Figure 4, line by line):
2: Specifying that this is a mapping file
3: Specifying the class and the table we are mapping from. Please note that it is required to enter the fully qualified class name followed by a comma, and then add the assembly name. The assembly name can be found by right-clicking on the project -> Properties ->Assembly name. This is important, too! Don’t worry about the lazy=true attribute, we’ll take care of that later.
4-6: Indicates that the PK id of the rows in the table belongs to the property Id of class Book. The generator tag just tells nhibernate that we are going to use our DBs unique id generator by default for creating new rows. This will be used once we create an object and save it to DB.
7-8: Property mappings. Where name attribute indicates the property’s name we’re mapping towards, and column attribute indicates the DB column we’re mapping from.
This is it already. Now we’ll head on to the final part of this issue: Crea
2.4 Creating the Configuration File
The purpose of creating this file is that we need to establish a connection to our database, hence we must provide driver, DB name, login credentials etc. for nhibernate.
Right-click on the project, go to Add new item -> Application Configuration File. Leave the name as it is (App.config, see Figure 5)
The newly created file looks like in Figure 6.
Figure 5: Creating the application configuration file.
Figure 6: The empty App.config
Now, let’s complete the App.config’s code:
1: <?xml version="1.0"?>
6: <section name="hibernate-configuration"
7: type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
10: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
13: <property name="connection.provider">
17: <property name="connection.driver_class">
21: <property name="connection.connection_string">
22: Data Source=.\SQLEXPRESS;
24: Integrated Security=True;
25: Connect Timeout=30;
26: User Instance=True
29: <property name="dialect">
33: <property name="proxyfactory.factory_class">
42: <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
Snippet 1: The configuration file.
As you can see, the App.config sections specify mostly the database connection modality, i.e. which driver to use, which connection provider, as well as the connection string.
Important: You do not have to write the connection string manually, but can simply copy it from the database explorer. There you simply right-click your database file, choose Properties, and copy the connection string from the corresponding field. In the example, I only split it up by semicolons in order to make it more readable; however: You should leave it as a one-liner.
Now, let’s write the Program class:
1: using System;
3: using System.Collections.Generic;
5: using System.Linq;
7: using System.Text;
9: using NHibernate;
11: using NHibernate.Cfg;
13: using System.Reflection;
15: namespace DevJour1
17: class Program
19: static ISessionFactory s;
20: static void Main(string args)
22: Book b = new Book();
23: b.Title = "Pulse";
24: b.Author = "King";
25: ISession session = OpenSession();
30: Console.WriteLine(b.Title + "was successfully saved to DB.");
32: catch (Exception e)
38: static ISession OpenSession()
40: if (s == null)
42: Configuration configuration = new Configuration();
44: s= configuration.BuildSessionFactory();
46: return s.OpenSession();
Snippet 2: Usage of our mapped entity. In this case, it is used for making an object of class Book persistent to the database.
2.5 Explanation of the Program class (snippet 2, line by line)
Premise: In order to execute queries, insertions (as in Snippet 1, the session’s Save method), updates or deletes, we need an object of which implements the ISession interface. ISession is part of the nhibernate API, and the OpenSession() method simply returns an instance of such, w.r.t. the current assembly that we are working from.
21-24: Construct a new object of type Book and set its properties manually
25: Retrieve the ISession by calling OpenSession()
27-36: Calling the Save method and passing Book b as parameter. We perform some basic exception handling to see whether we did everything correctly. If no exception is thrown, we are fine.
That was already the essence of this code. We just created a .NET object and saved it to our database. In fact, we did so only about 50 lines of code (and another 45 for the mapping file).
Quite simple, wasn’t it?
Next time, in part 3, we’ll have a look on how to query the objects from DB and at the different ways we can execute queries.
Stay tuned for more nhibernate parts!