Nhibernate
Author: d | 2025-04-24
NHIBERNATE PROFILER is a tool for monitoring the SQL statement in NHIBERNATE. 1, download NHibernate Profiler. 2, add a reference in your NHibernate project (below the NHibernate Object Relational Mapper. Contribute to nhibernate/nhibernate-core development by creating an account on GitHub.
nhibernate/nhibernate-core: NHibernate Object
Or two of code.NHibernate uses mapping files to guide its translation from the database to business objects and back again. As an alternative, you can use attributes on classes and properties, instead of mapping files. To keep things as simple as possible, we're going to use mapping files in this article, rather than attributes. In addition, mapping files make for a cleaner separation between business logic and persistence code.So, one need only add a few lines of code to an application and create a simple mapping file for each persistent class, and NHibernate takes care of all database operations. It is amazing how much development time is saved by using NHibernate.Note that NHibernate is not the only ORM framework in the .NET universe. There are literally dozens of commercial and open source products that provide the same services. NHibernate is among the most popular, probably because of its heritage as a descendant of Hibernate, a popular ORM Framework in the Java universe. In addition, Microsoft has promised an 'Entity Framework' for ADO.NET, to provide ORM services. However, the product has been delayed, and it may not be released for some time.Installing NHibernateThe first step in using NHibernate is to download NHibernate and Log4Net, an open-source logging application that NHibernate can use to record errors and warnings. NHibernate contains the most recent Log4Net binary, or you can download the entire Log4Net install package. Here are the download locations:NHibernateLog4Net Log4Net is not strictly required to use NHibernate, but its automatic logging can be very useful when debugging. Getting StartedIn this article, I am going to use a very simple demo application (the demo app) that does no real work, other than demonstrating data access with NHibernate. It is a console application, which simplifies things by eliminating UI code. The application creates some
NHibernate 2.1.0Beta2 - NHibernate
Business objects, uses NHibernate to persist them, and then reads them back from the database. You will need to do several things to run the demo app on your machine:Replace references to NHibernate and Log4NetAttach the NhibernateSimpleDemo databaseModify the connection stringThe demo app contains references to NHibernate and Log4Net. The references should be valid on your PC, so long as NHibernate and Log4Net are installed in their default locations. If the references aren't valid, you will need to replace them with references to NHibernate (NHibernate.dll) and Log4Net (log4net.dll) as they are installed on your PC. The DLLs can be found in the NHibernate installation folder on your development PC. The demo app is configured to use SQL Server Express 2005. The database files (NhibernateSimpleDemo.mdf and NhibernateSimpleDemo.ldf) are packaged with the demo app. You will need to attach the database to SQL Server on your machine.Finally, the connection string in the App.config file assumes that you are running a named instance of SQL Server Express 2005, and that the instance is named 'SQLEXPRESS'. If your PC is running a different configuration of SQL Server 2005, you will need to modify the connection string in the App.config file. Note that the database will not work with older versions of SQL Server.The Business ModelThere are two ways to develop an application with NHibernate. The first is a "data-centric" approach, which starts with a data model and creates business objects from the database. The second is an "object-centric" approach, which starts with a business model and creates a database to persist the model. The demo app uses the object-centric approach.Here is the business model for the demo app:The model represents the skeleton of an order system. The model is not complete—there are just enough classes to demonstrate object persistence with NHibernate. And there isGitHub - nhibernate/nhibernate-core: NHibernate Object
To print a list of customers and orders whenever the business model is reloaded or rebuilt.Once the model has been built, the application saves it. And it is here that NHibernate really shines. The Save() method in the PersistenceManager shows how simple persistence code can be with NHibernate. We don't even have to think about the database. The Controller simply tells the PersistenceManager to save our objects:private static void SaveBusinessObjects (OrderSystem OrderSystem, PersistenceManager persistenceManager){ foreach (Product product in OrderSystem.Catalog) { persistenceManager.Save(product); } foreach (Customer Customer in OrderSystem.Customers) { persistenceManager.Save(Customer); }}Note that the SaveBusinessObjects() method saves Products and Customers, but not Orders. Since we have turned cascading on for the Customer.Orders property, Customers' orders are saved automatically when Customers are saved. So, there is no need to save the Order objects in the OrderSystem.Orders list.Note also that NHibernate takes care of creating records for the OrderItems table in the database, even though we don't have any code that instructs it to do so. That is because the Order mapping file specifies the OrderItems table as the link table in the many-to-many association contained in the Order.OrderItems property. And that is another example of how NHibernate simplifies persistence code.Deleting Business ObjectsAfter saving the business model, the application clears it from RAM. We do this to set up the next demo, but it also illustrates an important point: Deleting a business object from RAM does not remove its data from the database. As we will see below, we have to explicitly instruct NHibernate to remove an object from the database. If we simply delete the business object from RAM, NHibernate can reload the business object from the database at any time. That is the subject of our next demonstration.Loading Objects with NHibernateOnce the business model has been deleted from RAM, the application reloads. NHIBERNATE PROFILER is a tool for monitoring the SQL statement in NHIBERNATE. 1, download NHibernate Profiler. 2, add a reference in your NHibernate project (below theNHibernate - Browse /NHibernate at SourceForge.net
Log4NetYou may recall that we imported a reference to Log4Net into the demo app project when we set it up. The first step to configuring NHibernate is to configure Log4Net. Note that if you use Log4Net (its use is optional), Log4Net must be configured before NHibernate, since NHibernate will expect to see Log4Net when it is initialized.Log4Net configuration is easy. First, make sure that Log4Net is enabled in the App.config file:logger name="NHibernate">level value="DEBUG" />/logger>Next, add the following attribute to your code. The demo app adds it above the namespace declaration for the PersistenceManager class:[assembly: log4net.Config.XmlConfigurator(Watch=true)]namespace NHibernateSimpleDemo{ public class PersistenceManager : IDisposable { … }The final step to configuring Log4Net is to call its Configure() method. The demo app encapsulates the call in a ConfigureLog4Net() method, which is called from the PersistenceManager constructor:private void ConfigureLog4Net(){ log4net.Config.XmlConfigurator.Configure();}Configuring NHibernate – Configuration CodeThe demo app configures NHibernate when it initializes the PersistenceManager. The PersistenceManager does the configuration in a private method, which is called from the PersistenceManager constructor. The configuration code is straightforward:private void ConfigureNHibernate(){ Configuration cfg = new Configuration(); cfg.Configure(); Assembly thisAssembly = typeof(Customer).Assembly; cfg.AddAssembly(thisAssembly); m_SessionFactory = cfg.BuildSessionFactory();}First, we create an NHibernate Configuration object. Then we pass it the class mappings from the mapping files. Note that the AddAssembly() method requires that all mapping files be embedded in the project assembly. To do this, set the BuildAction property of each mapping file to Embedded Resource.Once we have passed mapping files to the Configuration object, we simply need to tell it to create a SessionFactory for us. NHibernate will find and read the configuration data it needs; we do not need to specify whether the data is found in App.config or in a separate XML file, and we do not need to explicitly load the data.BuildSessionFactory() returns a SessionFactory object, which the demo appNHibernate 5.5 Released - NHibernate
Able to complete configuring NHibernate, you will know it had no problems with your mapping documents. We discuss configuration below.Note that if NHibernate complains that one of your classes is unmapped, even though you have created a mapping file for that class, check the declaration in the mapping file, to make sure you entered the name of the class and its mapping table correctly. If those are correct, verify that you set the file's Build Action property to Embedded Resource.Integrating NHibernateThere is no single 'right' way to integrate NHibernate into your application. The author's personal preference is to follow general three-tier architecture, and to place NHibernate configuration and processing code in a data tier. The demo app has a Persistence folder, which contains a PersistenceManager class. The PersistenceManager contains generic methods to persist each of the entities in the business model. While a single class is sufficient for the demo app, it is probably not best practice for a production application. In a real-world app, you may want to split these methods out to several persistence classes.The PersistenceManager class configures NHibernate and holds a global reference to a SessionFactory object. A SessionFactory creates Session objects. Sessions are the basic NHibernate unit of work. A session represents a conversation between your application and NHibernate.You can think of them as being one level up in a hierarchy from a transaction. A session generally encompasses one transaction, but it can include several. Basically, you open a NHibernate session, execute one or several transactions, close the session, and dispose it.Sessions are created by a SessionFactory object. A SessionFactory is resource intensive and has a relatively high initialization cost. Sessions, on the other hand, use limited resources and impose little initialization cost. So, the general approach is to create a global SessionFactory when the applicationNHibernate 4.0.3 Released - NHibernate
Feature, which can be implemented in a variety of retrieval methods to retrieve 'like' string, or values within a specified range.Delete(): This method has two overloads. The first deletes a single object passed into it. The second deletes a list of objects passed into it.Most of the methods follow a common pattern:They wrap a new NHibernate session object in a using statement. The using statement ensures that the session is properly closed and disposed when the method is through with it, even if an exception is thrown. The method RetrieveAll() is an exception, which we discuss below.The Save() and Delete() methods further wrap an NHibernate transaction in a using statement, for the same reason.The method calls a generic method of the NHibernate session object, in order to perform the work that needs to be done.Note that the PersistenceManager includes a Close() method, and that it implements the IDisposible interface. That means the PersistenceManager must be closed and disposed when the application is finished with it, which the demo app does.The CRUD methods in the PersistenceManager are not intended to represent a complete implementation of object persistence. The CRUD methods are intended to show the basics of how persistence works in NHibernate. The NHibernate documentation contains complete information about the CRUD methods provided by the session object and how to implement those methods in your application.The PayoffAt this point, you may be asking yourself, as I did, whether NHibernate has such a complicated setup that it might be just as easy to write CRUD code by hand. I personally found NHibernate's learning curve to be rather steep and slow going.Well, here is where it all pays off. If you think about what we have done so far, it is really little more than creating some short mapping files, and adding aGitHub - nhibernate/NHibernate.Mapping.Attributes: With NHibernate
Date that NHibernate uses is contained in separate XML files. This approach loosens the coupling between business classes and data-access classes, resulting in a more flexible, easier-to-maintain business tier. The only requirement that NHibernate imposes is that collections be typed to interfaces, rather than concrete types. That's a practice that is generally recommended for all OO programming, and it does not bind business classes to NHibernate in any way.The DatabaseHere is the database that the demo app uses to persist the model:Note that the database and the object model do not match perfectly. The object model has an Address class that has no corresponding table in the database, and the database has an OrderItems table that has no corresponding class. This mismatch is intentional. One of the aspects of NHibernate that we want to show is that there need not be a one-to-one correspondence between classes and database tables.Here are the reasons for the mismatch:The Address class does not represent an entity in the business model. Instead, it represents a value held in an entity, in this case, the Customer.Address property. We encapsulated the address in a separate class so that we can demonstrate what NHibernate calls "component mapping".The OrderItems table is a link table in a many-to-many relationship between Orders and Products. As such, it does not represent an entity from the business model.The Customers table contains a skeleton of the usual customer information, including the customer's address. Best practice would call for the address in a separate table, contrary to what we have done here. We included address information in the Customers table so we could demonstrate how to persist what NHibernate calls 'components'—classes that do not have their own tables. We will discuss components in more detail below.The Orders table has a bare minimum of information; only. NHIBERNATE PROFILER is a tool for monitoring the SQL statement in NHIBERNATE. 1, download NHibernate Profiler. 2, add a reference in your NHibernate project (below the
Releases nhibernate/nhibernate-core - GitHub
Is initialized, and use that SessionFactory to create session objects as needed. The demo project initializes a PersistenceManager object as part of the application initialization. The PersistenceManager configures a SessionFactory, which becomes a member variable of the PersistenceManager. The application can call PersistenceManager.SessionFactory to create sessions as needed.Configuring NHibernate – Configuration DataThere are two elements to configuring NHibernate:Configuration dataConfiguration codeConfiguration data can be placed either in a separate configuration file in the application root directory, or in the App.config file for the application. To keep things simple, the demo app places the data in the App.config file. It means one less file to get lost or separated from the rest of the application.At the beginning of this article, we suggested downloading Log4Net along with NHibernate. Log4Net has its own configuration data, which we will place in the App.config folder as well. The Log4Net configuration data is straightforward, so we will not cover it here. Note that both NHibernate and Log4Net need tags in App.config's section.NHibernate's configuration data is reasonably clear. The data is used by NHibernate to create a SessionFactory. Here are the SessionFactory properties that are set from the data:Connection provider: The IConnectionProvider that NHibernate should use. The demo app uses the default provider.Dialect: Which database dialect to use. The demo app specifies the SQL Server 2005 dialect.Connection driver: Which ADO.NET driver to use. The demo app specifies the SQL Server client driver.Connection string: The connection string to use in connecting with the database. The connection string is a standard ADO.NET connection string; you do not need to modify a valid connection string to use it with NHibernate.Note that the connection string in the demo app is valid for the author's development environment. You will need to change the connection string to match your database setup.Configuring NHibernate – Configuringnhibernate Tutorial = Getting started with nhibernate
Did before, and reloads the object model from the database. This time, there are only two Customers, and only two Orders. Not only did NHibernate delete the Able, Inc. Customer record from the database, but it deleted Able, Inc.'s Orders, and the OrderItems in those orders, as well.Putting The Focus Back Where It BelongsWe have completed our tour of basic CRUD operations with NHibernate. I hope you come away with the following point: NHibernate will dramatically simplify the persistence layer of your application. Once you have created mapping files for your classes, you can nearly forget about persistence. And you don't have to spend days or weeks coding a cumbersome persistence layer to get those benefits. The persistence tier of the demo app illustrates how lightweight this tier can be when using NHibernate. We have only a few methods, and most of those are generic, reducing the need for overloads or creating a persistence class for each business model class. The methods themselves are simple, and do not require much time to design or code. The amount of work that you have to do to persist your objects is slashed. Not bad for a free piece of software!But there is another benefit, and it may be the most important. Take a look at the demo project in VS 2005's Solution Explorer, and you will see that most of the application's work is being done in the model. The Controller simply manages the work and delegates tasks to the business model and the persistence manager, which is basically just a thin wrapper for NHibernate. As a result, you are free to devote nearly all your attention to your business model. By relieving you of the chore of writing persistence code, NHibernate enables you to keep your focus on your business model,. NHIBERNATE PROFILER is a tool for monitoring the SQL statement in NHIBERNATE. 1, download NHibernate Profiler. 2, add a reference in your NHibernate project (below the NHibernate Object Relational Mapper. Contribute to nhibernate/nhibernate-core development by creating an account on GitHub.nhibernate Tutorial = LINQ to NHibernate Queries
Where it belongs. Where To Go From HereWe have really just scratched the surface of NHibernate. Even so, you should have enough to get going. Play around with it on a couple of demo projects of your own, to get a feel for how it works. At that point you should be ready to dive into the documentation for the framework.NHibernate ships with two documentation files. The first is a general explanation of the Framework, and the second is a reference to NHibernate's API. In addition, Manning Publications publishes NHibernate in Action (ISBN: 1-932394-92-3), which provides an extensive and detailed explanation of the Framework. It is available in eBook now and it is scheduled to appear in paperback in December 2007.As you delve further into NHibernate, be sure to learn about lazy loading and how it works. As we discussed above, lazy loading is essential to the efficient use of NHibernate, and it is well worth the time to learn.ConclusionI hope you have enjoyed this introduction to NHibernate, and that it will flatten the learning curve involved in getting up to speed with the Framework. Please post comments and questions on Code Project, and I will answer as many as I can. If you find any errors, please post a comment, so that I can correct it in a revised version of the article.Comments
Or two of code.NHibernate uses mapping files to guide its translation from the database to business objects and back again. As an alternative, you can use attributes on classes and properties, instead of mapping files. To keep things as simple as possible, we're going to use mapping files in this article, rather than attributes. In addition, mapping files make for a cleaner separation between business logic and persistence code.So, one need only add a few lines of code to an application and create a simple mapping file for each persistent class, and NHibernate takes care of all database operations. It is amazing how much development time is saved by using NHibernate.Note that NHibernate is not the only ORM framework in the .NET universe. There are literally dozens of commercial and open source products that provide the same services. NHibernate is among the most popular, probably because of its heritage as a descendant of Hibernate, a popular ORM Framework in the Java universe. In addition, Microsoft has promised an 'Entity Framework' for ADO.NET, to provide ORM services. However, the product has been delayed, and it may not be released for some time.Installing NHibernateThe first step in using NHibernate is to download NHibernate and Log4Net, an open-source logging application that NHibernate can use to record errors and warnings. NHibernate contains the most recent Log4Net binary, or you can download the entire Log4Net install package. Here are the download locations:NHibernateLog4Net Log4Net is not strictly required to use NHibernate, but its automatic logging can be very useful when debugging. Getting StartedIn this article, I am going to use a very simple demo application (the demo app) that does no real work, other than demonstrating data access with NHibernate. It is a console application, which simplifies things by eliminating UI code. The application creates some
2025-03-29Business objects, uses NHibernate to persist them, and then reads them back from the database. You will need to do several things to run the demo app on your machine:Replace references to NHibernate and Log4NetAttach the NhibernateSimpleDemo databaseModify the connection stringThe demo app contains references to NHibernate and Log4Net. The references should be valid on your PC, so long as NHibernate and Log4Net are installed in their default locations. If the references aren't valid, you will need to replace them with references to NHibernate (NHibernate.dll) and Log4Net (log4net.dll) as they are installed on your PC. The DLLs can be found in the NHibernate installation folder on your development PC. The demo app is configured to use SQL Server Express 2005. The database files (NhibernateSimpleDemo.mdf and NhibernateSimpleDemo.ldf) are packaged with the demo app. You will need to attach the database to SQL Server on your machine.Finally, the connection string in the App.config file assumes that you are running a named instance of SQL Server Express 2005, and that the instance is named 'SQLEXPRESS'. If your PC is running a different configuration of SQL Server 2005, you will need to modify the connection string in the App.config file. Note that the database will not work with older versions of SQL Server.The Business ModelThere are two ways to develop an application with NHibernate. The first is a "data-centric" approach, which starts with a data model and creates business objects from the database. The second is an "object-centric" approach, which starts with a business model and creates a database to persist the model. The demo app uses the object-centric approach.Here is the business model for the demo app:The model represents the skeleton of an order system. The model is not complete—there are just enough classes to demonstrate object persistence with NHibernate. And there is
2025-04-10Log4NetYou may recall that we imported a reference to Log4Net into the demo app project when we set it up. The first step to configuring NHibernate is to configure Log4Net. Note that if you use Log4Net (its use is optional), Log4Net must be configured before NHibernate, since NHibernate will expect to see Log4Net when it is initialized.Log4Net configuration is easy. First, make sure that Log4Net is enabled in the App.config file:logger name="NHibernate">level value="DEBUG" />/logger>Next, add the following attribute to your code. The demo app adds it above the namespace declaration for the PersistenceManager class:[assembly: log4net.Config.XmlConfigurator(Watch=true)]namespace NHibernateSimpleDemo{ public class PersistenceManager : IDisposable { … }The final step to configuring Log4Net is to call its Configure() method. The demo app encapsulates the call in a ConfigureLog4Net() method, which is called from the PersistenceManager constructor:private void ConfigureLog4Net(){ log4net.Config.XmlConfigurator.Configure();}Configuring NHibernate – Configuration CodeThe demo app configures NHibernate when it initializes the PersistenceManager. The PersistenceManager does the configuration in a private method, which is called from the PersistenceManager constructor. The configuration code is straightforward:private void ConfigureNHibernate(){ Configuration cfg = new Configuration(); cfg.Configure(); Assembly thisAssembly = typeof(Customer).Assembly; cfg.AddAssembly(thisAssembly); m_SessionFactory = cfg.BuildSessionFactory();}First, we create an NHibernate Configuration object. Then we pass it the class mappings from the mapping files. Note that the AddAssembly() method requires that all mapping files be embedded in the project assembly. To do this, set the BuildAction property of each mapping file to Embedded Resource.Once we have passed mapping files to the Configuration object, we simply need to tell it to create a SessionFactory for us. NHibernate will find and read the configuration data it needs; we do not need to specify whether the data is found in App.config or in a separate XML file, and we do not need to explicitly load the data.BuildSessionFactory() returns a SessionFactory object, which the demo app
2025-04-15Able to complete configuring NHibernate, you will know it had no problems with your mapping documents. We discuss configuration below.Note that if NHibernate complains that one of your classes is unmapped, even though you have created a mapping file for that class, check the declaration in the mapping file, to make sure you entered the name of the class and its mapping table correctly. If those are correct, verify that you set the file's Build Action property to Embedded Resource.Integrating NHibernateThere is no single 'right' way to integrate NHibernate into your application. The author's personal preference is to follow general three-tier architecture, and to place NHibernate configuration and processing code in a data tier. The demo app has a Persistence folder, which contains a PersistenceManager class. The PersistenceManager contains generic methods to persist each of the entities in the business model. While a single class is sufficient for the demo app, it is probably not best practice for a production application. In a real-world app, you may want to split these methods out to several persistence classes.The PersistenceManager class configures NHibernate and holds a global reference to a SessionFactory object. A SessionFactory creates Session objects. Sessions are the basic NHibernate unit of work. A session represents a conversation between your application and NHibernate.You can think of them as being one level up in a hierarchy from a transaction. A session generally encompasses one transaction, but it can include several. Basically, you open a NHibernate session, execute one or several transactions, close the session, and dispose it.Sessions are created by a SessionFactory object. A SessionFactory is resource intensive and has a relatively high initialization cost. Sessions, on the other hand, use limited resources and impose little initialization cost. So, the general approach is to create a global SessionFactory when the application
2025-04-11Date that NHibernate uses is contained in separate XML files. This approach loosens the coupling between business classes and data-access classes, resulting in a more flexible, easier-to-maintain business tier. The only requirement that NHibernate imposes is that collections be typed to interfaces, rather than concrete types. That's a practice that is generally recommended for all OO programming, and it does not bind business classes to NHibernate in any way.The DatabaseHere is the database that the demo app uses to persist the model:Note that the database and the object model do not match perfectly. The object model has an Address class that has no corresponding table in the database, and the database has an OrderItems table that has no corresponding class. This mismatch is intentional. One of the aspects of NHibernate that we want to show is that there need not be a one-to-one correspondence between classes and database tables.Here are the reasons for the mismatch:The Address class does not represent an entity in the business model. Instead, it represents a value held in an entity, in this case, the Customer.Address property. We encapsulated the address in a separate class so that we can demonstrate what NHibernate calls "component mapping".The OrderItems table is a link table in a many-to-many relationship between Orders and Products. As such, it does not represent an entity from the business model.The Customers table contains a skeleton of the usual customer information, including the customer's address. Best practice would call for the address in a separate table, contrary to what we have done here. We included address information in the Customers table so we could demonstrate how to persist what NHibernate calls 'components'—classes that do not have their own tables. We will discuss components in more detail below.The Orders table has a bare minimum of information; only
2025-04-20