NHibernate – Profiler

NHibernate – Profiler ”; Previous Next In this chapter, we will be understanding how all the records from the database are retrieved, updated, created, and deleted and how exactly these queries are performed? To understand all these, we can simply add an option into our configuration, which logs the SQL in the console. Here is the simple statement that will log the SQL query − x.LogSqlInConsole = true; Now, we have two records in our student table in the NHibernateDemoDB database. Let’s retrieve all the records from the database as shown in the following code. using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { var cfg = new Configuration(); String Data Source = asia13797\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = “Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.LogSqlInConsole = true; }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { Console.WriteLine(“nFetch the complete list againn”); var students = session.CreateCriteria<Student>().List<Student>(); foreach (var student in students) { Console.WriteLine(“{0} t{1} t{2}”, student.ID, student.FirstMidName, student.LastName); } tx.Commit(); } Console.ReadLine(); } } } } So let”s go ahead and run this application again, and you will see the following output − NHibernate: SELECT this_.ID as ID0_0_, this_.LastName as LastName0_0_, this_.FirstMidName as FirstMid3_0_0_ FROM Student this_ Fetch the complete list again 3 Allan Bommer 4 Jerry Lewis As you can see, the select clause being sent to the database, it is actually like clause which will retrieve the ID, FirstMidName and LastName. So all this is being sent to the database and processed there rather than having a lot of records brought back to your server and processed on the server side. NHibernate Profiler Another way to look at these results is to use NHibernate Profiler. NHibernate Profiler is a commercial tool, but is it very useful for working with NHibernate applications. You can easily install the NHibernate Profiler into your application from NuGet. Let’s go to the NuGet Manager console from the Tools menu by selecting the NuGet Package Manager → Package Manager Console. It will open the Package Manager Console window. Enter the following command and press enter. PM> install-package NHibernateProfiler It will install all the required binaries for the NHibernate Profiler, once it is successfully installed you will see the following message. You will also see that the NHibernate Profiler is launched, once it is installed. It will require a license to use it, but for demo purposes, we can use the 30-days trial version of NHibernate Profiler. Now, NHibernate Profiler is optimized to work with web applications and you will see that it has added App_Start folder in the solution explorer. To keep all these simple, delete the App_Start folder and also you will observe that one statement is added at the start of the Main method in Program class. App_Start.NHibernateProfilerBootstrapper.PreStart(); Remove this statement as well and just add a simple call NHibernateProfiler.Initialize as shown in the following code. using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { NHibernateProfiler.Initialize(); var cfg = new Configuration(); String Data Source = asia13797\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = “Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.LogSqlInConsole = true; }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()){ var students = session.CreateCriteria<Student>().List<Student>(); Console.WriteLine(“nFetch the complete list againn”); foreach (var student in students) { Console.WriteLine(“{0} t{1} t{2}”, student.ID, student.FirstMidName, student.LastName); } tx.Commit(); } Console.ReadLine(); } } } } Now when you run the application, it”s going to send data over to the NHibernate Profiler application. You can see here, we”ve got a nice display that shows that we”ve started the transaction, what the SQL is doing to the database in a nice format. So this is very useful for determining what exactly is happening inside of your NHibernate application. It becomes incredibly useful once the application gets to a certain level of complexity, where you need something more like a SQL Profiler, but with the knowledge of NHibernate. Print Page Previous Next Advertisements ”;

NHibernate – Configuration

NHibernate – Configuration ”; Previous Next In this chapter, we will look at NHibernate configuration. We have different ways that we can configure NHibernate. It divides into two main groups XML-based configuration Code-based configuration Code-Based Configuration The code-based configuration is built into NHibernate. It was introduced around the NHibernate 3 and we have used the code bases configuration up till now. String Data Source = asia13797\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = “Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.LogSqlInConsole = true; }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); All the configurations are specified in the C# code. You can see here that we have got our new configuration object, and then we use loquacious configuration that was introduced with NHibernate 3.1 to configure the database. What connection string we are using, what database we are connecting to and the dialect to use. We also add our mapping assembly directly to here. XML-Based Configuration If you are using XML-based configuration, you can use a hibernate.cfg.xml file, which is just a standalone xml file using the NHibernate schema, or you can embed that NHibernate specific configuration inside of your app or web.cfg. The hibernate.cfg.xml name is by default, but we can use an arbitrary name for that xml file as well. Let’s have a look into the XML-based configuration by adding a new xml file to the NHibernateDemoApp project and call it hibernate.cfg.xml. Enter the following information into the hibernate.cfg.xml file. <?xml version = “1.0” encoding = “utf-8” ?> <hibernate-configuration xmlns = “urn:nhibernate-configuration-2.2”> <session-factory> <property name = “connection.connection_string”> Data Source = asia13797\sqlexpress; Initial Catalog = NHibernateDemoDB; Integrated Security = True; Connect Timeout = 15; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False; </property> <property name = “connection.driver_class”> NHibernate.Driver.SqlClientDriver </property> <property name = “dialect”> NHibernate.Dialect.MsSql2008Dialect </property> <mapping assembly = “NHibernateDemoApp”/> </session-factory> </hibernate-configuration> As you can see in the above xml file, we have specified the same configuration as mentioned in the C#. Now let’s comment on this configuration from the Program.cs file and just call the Configure() method, which will load the hibernate.cfg.xml file as shown below. using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { NHibernateProfiler.Initialize(); var cfg = new Configuration(); //cfg.DataBaseIntegration(x => //{ // x.ConnectionString = “Data Source = asia13797;\sqlexpress Initial Catalog = NHibernateDemoDB; Integrated Security = True; Connect Timeout = 15; Encrypt =False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False”; // x.Driver<SqlClientDriver>(); // x.Dialect<MsSql2008Dialect>(); // x.LogSqlInConsole = true; //}); //cfg.AddAssembly(Assembly.GetExecutingAssembly()); cfg.Configure(); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); Console.WriteLine(“nFetch the complete list againn”); foreach (var student in students) { Console.WriteLine(“{0} t{1} t{2} t{3}”, student.ID, student.FirstName, student.LastName, student.AcademicStanding); } tx.Commit(); } Console.ReadLine(); } } } } Let’s run your application again and you will see the same output. Fetch the complete list again 1 Allan Bommer Excellent 2 Jerry Lewis Good Print Page Previous Next Advertisements ”;

NHibernate – Orm

NHibernate – ORM ”; Previous Next Before we can really start using NHibernate, we need to understand the foundation on which it is built. NHibernate is a persistence technology that is based on the idea of object relational mapping or ORM. What is ORM? Object-Relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages. In other words, it is the concept of mapping an application”s business objects to relational database tables, so that the data can be easily accessed and updated entirely through the object model of an application. As you already know that relational databases provide a good means of storing data, while object-oriented programming is a good approach to building complex applications. NHibernate and ORM in general are most relevant to applications with nontrivial business logic, the domain model and some sort of database. With ORM, it is very easy to create a translation layer that can easily transform objects into relational data and back again. The acronym ORM can also mean object role modeling, and this term was invented before object/relational mapping became relevant. It describes a method for information analysis, used in database modeling. Why ORM? ORM is a framework that enables you to map the world of objects found in object oriented languages to rows in relational tables found in relational databases To understand this concept, let”s have a look at the following diagram. In the above diagram, you can see that we have a table called Employee on the right side that contains columns with each piece of data associated with an individual employee. We have a column for an Id which uniquely identifies each employee. A column for the employee’s name, another column for their joining date, and finally a column that has an age of an employee. If we wanted to write some code to store a new employee in the tables, it isn”t so easy. In the above diagram, you can also see that we have an employee object that has fields for the Id, name, joining date and age. Without an ORM we have to translate this object into a few different SQL statements that will insert the employee data into the employee table. So writing code to create the SQL to do the above scenario is not that hard, but it is a bit tedious and pretty easy to get wrong. Using an ORM like NHibernate, we can declare how certain classes should be mapped to relational tables and let the ORM or NHibernate deal with the nasty job of creating the SQL to insert, update, delete, in query data in our employee table. This allows us to keep our code focused on using objects and have those objects automatically translated to relational tables. So really what an ORM does is it saves us from manually having to map objects to tables. Print Page Previous Next Advertisements ”;

NHibernate – Overview

NHibernate – Overview ”; Previous Next In this chapter, we will discuss about what NHibernate is, which all platforms it can be implemented, what are its advantages and other aspects related to it. What is NHibernate? NHibernate is a mature, open source object-relational mapper for the .NET framework. It”s actively developed, fully featured and used in thousands of successful projects. It”s built on top of ADO.NET and the current version is NHibernate 4.0.4. NHibernate is an open-source .NET object-relational mapper and is distributed under the GNU Lesser General Public License. It is based on Hibernate which is a popular Java object-relational mapper and it has a very mature and active code base. It provides a framework for mapping an object-oriented domain model to a traditional relational database. NHibernate was started by Tom Barrett and this project has been around since February of 2003, which was their first commit. It”s a big project and provides a lot of functionality. There is a NuGet package available, which makes it very easy to add to a project. Why NHibernate? Now the question is why do we need object-relational mappers? It is because there is a disconnect between the object world and the relational world. In the object world, everything is based around objects; we called objects those things which have our data. The relational world is all set-based and we are dealing with tables and rows which are different than the object world. In the object world, we have unidirectional associations. If a customer has a pointer to an order, it doesn”t necessarily mean that an order has a pointer back to a customer, it might or might not. In the relational world, all associations are bidirectional and it can be done by a foreign key. All associations are inherently bidirectional, so when we are dealing with object-relational mapping, we also need to deal with this disconnect. In the object world, we are working with pointers that are unidirectional, whereas in with the relational world, we have foreign keys which are inherently bidirectional. The object world has this notion of inheritance, where a vehicle can have a number of different subclasses, so a car is a type of vehicle, a boat is a type of vehicle, and a sports car is a type of car, these types of inheritance relationships. The relational world doesn”t have this notion of inheritance. Mapping So how do we map all these disjoint relationships? This concept of mapping comes from the object-relational mapper. There are mainly three things to understand as shown in the following diagram. In your application, you will need class definitions, which is typically C# code and its .NET code that represents our classes, such as Employee class, Customer class, Order class, etc. At the bottom, you can see a database schema, which is our Data Definition Language in a relational database that specifies what a customer table looks like, what an employee table looks like. In between these we have the mapping metadata that tells the object-relational mapper how to translate from the object world in C# to the database world in terms of rows and columns and foreign key relationships. This mapping metadata can be represented in a variety of different ways and we will be looking at a number of this different ways most typical in NHibernate application. It is represented by HBM (Hibernate Mapping) files, which are XML files. Database Supported NHibernate supports a wide variety of different databases. Any existing relational database out there can be accessed to NHibernate. SQL server is the primary supported database, that”s what most developers are using during the development, it”s probably the most common one. It also works very well with Oracle. It also supports DB2, the Firebird, MySQL, PostgreSQL, SQL Lite It also has ODBC and OLEDB drivers. Print Page Previous Next Advertisements ”;