NHibernate – Inverse Relationships

NHibernate – Inverse Relationships ”; Previous Next In this chapter, we will be covering another feature which is Inverse Relationships. It is an amusing option that you will see on collection that are inversely equal to true and it also confuses a lot of developers. So let”s talk about this option. To understand this, you really have to think about the relational model. Let’s say you have a bidirectional associations using a single foreign key. From a relational standpoint, you have got one foreign key, and it represents both customer to order and orders to customer. From the OO model, you have unidirectional associations using these references. There is nothing that says that two unidirectional associations represent the same bidirectional association in the database. The problem here is that NHibernate doesn”t have enough information to know that customer.orders and order.customer represent the same relationship in the database. We need to provide inverse equals true as a hint, it is because the unidirectional associations are using the same data. If we try to save these relationships that have 2 references to them, NHibernate will try to update that reference twice. It will actually do an extra roundtrip to the database, and it will also have 2 updates to that foreign key. The inverse equals true tells NHibernate which side of the relationship to ignore. When you apply it to the collection side and NHibernate will always update the foreign key from the other side, from the child object side. Then we only have one update to that foreign key and we don”t have additional updates to that data. This allows us to prevent these duplicate updates to the foreign key and it also helps us to prevent foreign key violations. Let”s have a look at the customer.cs file in which you will see the AddOrder method and the idea here is that we now have this back pointer from order back to customer and it needs to be set. So when an order is added to a customer, that customer”s back pointer is set, otherwise, it would be null, so we need this to keep this connected properly together in the object graph. using System; using System.Text; using Iesi.Collections.Generic; namespace NHibernateDemo { public class Customer { public Customer() { MemberSince = DateTime.UtcNow; Orders = new HashedSet<Order>(); } public virtual Guid Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual double AverageRating { get; set; } public virtual int Points { get; set; } public virtual bool HasGoldStatus { get; set; } public virtual DateTime MemberSince { get; set; } public virtual CustomerCreditRating CreditRating { get; set; } public virtual Location Address { get; set; } public virtual ISet<Order> Orders { get; set; } public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; } public override string ToString() { var result = new StringBuilder(); result.AppendFormat(“{1} {2} ({0})rntPoints: {3}rntHasGoldStatus: {4}rntMemberSince: {5} ({7})rntCreditRating: {6}rntAverageRating: {8}rn”, Id, FirstName, LastName, Points, HasGoldStatus, MemberSince, CreditRating, MemberSince.Kind, AverageRating); result.AppendLine(“tOrders:”); foreach(var order in Orders) { result.AppendLine(“tt” + order); } return result.ToString(); } } public class Location { public virtual string Street { get; set; } public virtual string City { get; set; } public virtual string Province { get; set; } public virtual string Country { get; set; } } public enum CustomerCreditRating { Excellent, VeryVeryGood, VeryGood, Good, Neutral, Poor, Terrible } } Here is the Program.cs file implementation. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); Guid id; using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine(“New Customer:”); Console.WriteLine(newCustomer); session.Save(newCustomer); id = newCustomer.Id; tx.Commit(); } using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var query = from customer in session.Query<Customer>() where customer.Id == id select customer; var reloaded = query.Fetch(x => x.Orders).ToList().First(); Console.WriteLine(“Reloaded:”); Console.WriteLine(reloaded); tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Customer CreateCustomer() { var customer = new Customer { FirstName = “John”, LastName = “Doe”, Points = 100, HasGoldStatus = true, MemberSince = new DateTime(2012, 1, 1), CreditRating = CustomerCreditRating.Good, AverageRating = 42.42424242, Address = CreateLocation() }; var order1 = new Order { Ordered = DateTime.Now }; customer.AddOrder(order1); var order2 = new Order { Ordered = DateTime.Now.AddDays(-1), Shipped = DateTime.Now, ShipTo = CreateLocation() }; customer.AddOrder(order2); return customer; } private static Location CreateLocation() { return new Location { Street = “123 Somewhere Avenue”, City = “Nowhere”, Province = “Alberta”, Country = “Canada” }; } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } It is going to save that to the database and then reload it. Now let’s run your application and open the NHibernate Profiler and see how it actually saved it. You will notice that we have 3 groups of statements. The first one will insert the customer, and that customer”s ID is the Guid, which is highlighted. The second statement is insert into the orders table. You will notice the same Customer Id Guid is set in there, so have that foreign key set. The last statement is the update, which will update the foreign key to the same customer id once again. Now the problem is that the customer has the orders, and the orders has the customer, there”s no way that we haven”t told NHibernate that it”s actually the same relationship. The way we do this is with inverse equals true. So let”s go to our customer.hbm.xml mapping file and set the inverse equal to true as shown in the following code. <?xml version = “1.0” encoding = “utf-8” ?> <hibernate-mapping xmlns = “urn:nhibernate-mapping-2.2” assembly = “NHibernateDemo” namespace = “NHibernateDemo”> <class name = “Customer”> <id name = “Id”>

NHibernate – Getting Started

NHibernate – Getting Started ”; Previous Next In this chapter, we will look at how to start a simple example using NHibernate. We will be building a simple console application. To create a console application, we will use Visual Studio 2015, which contains all of the features you need to create, test your application using the NHibernate package. Following are the steps to create a project using project templates available in the Visual Studio. Step 1 − Open the Visual studio and click File → New → Project menu option. Step 2 − A new Project dialog opens. Step 3 − From the left pane, select Templates → Visual C# → Windows. Step 4 − In the middle pane, select Console Application. Step 5 − Enter the project name, ‘NHibernateDemoApp’, in the Name field and click Ok to continue. Step 6 − Once the project is created by Visual Studio, you will see a number of files displayed in the Solution Explorer window. As you know that we have created a simple console application project, now we need to include the NHibernate package to our console project. Go to the Tools menu and select NuGet Package Manager → Package Manager Console, it will open the Package Manager Console window. Specify the command shown in the above Package Manager Console window and press enter, it will download all the NHibernate dependencies and create references to all of the required assemblies. Once the installation is finished, you will see the message as shown in the following image. Now that we have NHibernate added, we can now start implementation. So, we are going to start out by mapping a very simple table called Student, which simply has an integer primary key called ID and a FirstName and LastName column. We need a class to represent this student, so let’s create a new class called Student by right clicking on the project in the solution explorer and then select Add → Class which will open the Add New Item dialog box. Enter Student.cs in the name field, click the Add button. In this Student class, we need to have our integer primary key called ID, and we need to create this string, FirstName and LastName fields as shown in the following complete implementation of Student class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NHibernateDemoApp { class Student { public virtual int ID { get; set; } public virtual string LastName { get; set; } public virtual string FirstMidName { get; set; } } } When dealing with models in NHibernate application, it is easiest to make all of your fields virtual. So this is our simple NHibernate model that we will use and will map this to the back end database. Now let’s go to the Main method in the Program class and create a new NHibernate configuration object. The first thing that we need to provide is the connection string. This is a database specific connection string and the easiest way to find the connection string is that right click on the database in SQL Server Object Explorer and select Properties. It will open the Properties Window, now scroll down and you will see the Connection String field in the Properties window. Copy the Connection string and specify in your code. Following is the implementation of Main method in which we need configuration for 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) { 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>(); }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { //perform database logic tx.Commit(); } Console.ReadLine(); } } } } After the connection string, we need to supply a driver, which is the SQLClientDriver and then we also need to provide it a dialect, which version of SQL Server, and we are going to use MS SQL 2008. NHibernate now knows how to connect to the database. The other thing we need to do is to provide it a list of models that we will map. We can do this by adding an assembly, so by specifying the Assembly.GetExecutingAssembly and this is where program will find mapping files. Mapping files tell NHibernate how to go from C# classes into database tables. SessionFactory compiles all the metadata necessary for initializing NHibernate. SessionFactory can be used to build sessions, which are roughly analogous to database connections. So the appropriate way is to use it in the using block. I can say var session equals sessionFactory.OpenSession and I”m going to want to do this inside of its transaction. Once the session is opened, we can tell the session to begin a new transaction and we can then perform some logic in here. So perform some database logic and finally commit that transaction. Print Page Previous Next Advertisements ”;

NHibernate – Environment Setup

NHibernate – Environment Setup ”; Previous Next To start working on NHibernate, we will need Visual Studio and the NHibernate package. Visual Studio Installation Microsoft provides a free version of Visual Studio, which also contains SQL Server and it can be downloaded from https://www.visualstudio.com Following are the steps for the installation. Step 1 − Once the downloading is completed then run the installer, then the following dialog box will be displayed. Step 2 − Click on the Install button and it will start installation process. Step 3 − Once the installation process is completed successfully, you will see the following dialog box. Step 4 − Close this dialog box and restart your computer if required. Step 5 − Now open Visual studio from the Start Menu which will open the following dialog. It will take some time for the first time for preparation. Step 6 − Once all this is done, you will see the main window of Visual Studio. NHibernate Package Installation NHibernate is a mature, open source object-relational mapper for the .NET framework. It is actively developed, fully featured and used in thousands of successful projects. You can install NHibernate package with the following methods. Direct Download Download the zip from file from https://sourceforge.net/ which contains all the binaries that are required. Extract this zip file and include all these binaries in your project. Install Using NuGet Another way of installing NHibernate is to use NuGet to install the NHibernate package, which is by far the easiest way to incorporate NHibernate into a project. It”s going to download all the NHibernate dependencies and create references to all of the required assemblies. To install NHibernate, run the following command in the Package Manager Console. install-package NHibernate You are now ready to start your application. Print Page Previous Next Advertisements ”;

NHibernate – Discussion

Discuss NHibernate ”; Previous Next NHibernate is an actively developed, fully featured, open source object-relational mapper for the .NET framework. It is used in thousands of successful projects. It”s built on top of ADO.NET and the current version is NHibernate 4.0.4. This tutorial will give you an idea of how to get started with NHibernate. The main goal is that after completing it, you will have a better understating of what NHibernate is and why you need NHibernate and of course learn how to add NHibernate to your project. Print Page Previous Next Advertisements ”;

NHibernate – Linq

NHibernate – Linq ”; Previous Next In this chapter, we will be covering another common API that people will use is the NHibernate LINQ provider. Its access through an extension method on ISession and the signature is a Query <T>. There are two types of syntax while using LINQ − Query Chaining Syntax Query Comprehension Syntax Query Chaining Syntax You can access any record from the database using the method chain syntax as shown in the following program. var customer = session.Query<Customer>() .Where(c => c.FirstName == “Laverne”) You can see that we have query, and also WHERE clause, you can have additional WHERE clauses and similarly select clause. This is a standard method chain syntax that you can use in normal LINQ. LINQ to Objects or LINQ to SQL, any of the other LINQ providers you might be familiar with. Let’s have a look into a simple example in which we will retrieve the customer whose first name is Laverne. Now it is a possibility that we might have more than one customer whose first name is Laverne, so we will retrieve the first one only. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customer = session.Query<Customer>() .Where(c => c.FirstName == “Laverne”).First(); Console.WriteLine(customer); tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Now when the above code is compiled and executed you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit… Query Comprehension Syntax There”s also the query comprehensions syntax, which looks a lot more like SQL using the from, where and select keywords. So let”s have a look into the same example, but this time we use LINQ comprehensions syntax, which looks a lot more like SQL as shown in the following program. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customer = (from c in session.Query<Customer>() where c.FirstName == “Laverne” select c).First(); Console.WriteLine(customer); tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Now let’s run this application again and you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit… Let’s have a look into another example in which we will retrieve all those customers, whose FirstName starts with the letter H. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.Query<Customer>() .Where(c =< c.FirstName.StartsWith(“H”)); foreach (var customer in customers.ToList()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Similarly, the query comprehension syntax will look like the following program. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = from c in session.Query<Customer>() where c.FirstName.StartsWith(“H”) select c; foreach (var customer in customers.ToList()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Let’s run this application again and you will see all the customers, whose first name starts with the alphabet H. Herman Crooks (4ead3480-6bce-11e1-b15c-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 12/3/2010 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ead3480-6bce-11e1-b15d-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15e-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15f-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b160-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b161-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b162-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b163-6cf049ee52be Hudson Bins (4ec03f80-6bce-11e1-b2b7-6cf049ee52be) Points: 56 HasGoldStatus: False MemberSince: 10/20/2008 12:00:00 AM (Utc) CreditRating: Terrible AverageRating: 0 Orders: Order Id: 4ec03f80-6bce-11e1-b2b8-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2b9-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2ba-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bb-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bc-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bd-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2be-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bf-6cf049ee52be Hettie Feest (4ec50240-6bce-11e1-b300-6cf049ee52be) Points: 82 HasGoldStatus: False MemberSince: 4/10/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ec50240-6bce-11e1-b301-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b302-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b303-6cf049ee52be Press <ENTER> to exit… Print Page Previous Next Advertisements ”;

NHibernate – QueryOver Queries

NHibernate – QueryOver Queries ”; Previous Next In this chapter, we will be covering QueryOver Queries. It is a new syntax which is more like LINQ using the method chain syntax as shown in the following query. var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == “Laverne”); It is still criteria under the covers, but now our queries are strongly typed. As we have seen in the criteria query, the first name is just an opaque string, now we”re actually using an x.FirstName, so the first name gets refactored and renamed that gets changed in the link style criteria query using the query over. We can still do many similar things, but you cannot use the query comprehension syntax with query over, you have to use the method chain syntax and you can”t mix and match the link and the criteria. For a lot of queries, the query over API is very useful and provides a much easier to comprehend object syntax than using Criteria directly. Let’s have a look into a simple example in which we will retrieve a customer whose first name is Laverne using a query over. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == “Laverne”); foreach (var customer in customers.List()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } As you can see that it is still Criteria underneath the covers, but is just a nicer syntax. When the above code is compiled and executed, you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit… One of the disadvantages is that, let”s say we want to say that FirstName.StartsWith(“A”) as shown in the following program. var customers = session.QueryOver<Customer>() .Where(x => x.FirstName.StartsWith(“A”)); foreach (var customer in customers.List()) { Console.WriteLine(customer); } tx.Commit(); Now let’s run the application again and you will see that this is not a LINQ provider as it doesn”t know what this StartsWith method is, so you will get a RunTime exception. The exception says unrecognized method call. Here we are doing the obvious thing, but it doesn”t necessarily work. Let”s try something else, like FirstName is equal to “A%” as shown in the following code. var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == “A%”); foreach (var customer in customers.List()) { Console.WriteLine(customer); } Let’s run this once again and you will see that we”re not going to get any results back as shown below. Press <ENTER> to exit… To understand this why we are not getting any results, let’s have a look at NHibernate profiler. As you can see that the first name is equal to A% which is not. A% is used in SQL using with the like operator. Now we need to create a restriction into WHERE clause as shown in the following program. var customers = session.QueryOver<Customer>() .Where(Restrictions.On<Customer>(c => c.FirstName).IsLike(“A%”)); foreach (var customer in customers.List()) { Console.WriteLine(customer); } Let’s run your application again and you will see that all the customers are retrieved with first name starts with A. Alejandrin Will (4ea3aef6-6bce-11e1-b0b4-6cf049ee52be) Points: 24 HasGoldStatus: False MemberSince: 10/1/2011 12:00:00 AM (Utc) CreditRating: VeryVeryGood AverageRating: 0 Orders: Order Id: 4ea3aef6-6bce-11e1-b0b5-6cf049ee52be Austyn Nolan (4ea871b6-6bce-11e1-b110-6cf049ee52be) Points: 67 HasGoldStatus: True MemberSince: 12/29/2007 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea871b6-6bce-11e1-b111-6cf049ee52be Antonia Murphy (4ea871b6-6bce-11e1-b121-6cf049ee52be) Points: 72 HasGoldStatus: True MemberSince: 6/15/2009 12:00:00 AM (Utc) CreditRating: Terrible AverageRating: 0 Orders: Order Id: 4ea871b6-6bce-11e1-b122-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b123-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b124-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b125-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b126-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b127-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b128-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b129-6cf049ee52be Order Id: 4ea871b6-6bce-11e1-b12a-6cf049ee52be It works the same way as it did before, except using this new QueryOver syntax. Many developers find that LINQ syntax is more approachable and often does the right things. If LINQ can”t handle it, then you will start looking at HQL or Criteria to see if that”s going to be more suitable. It just gives you a different syntax, so Criteria, both the create criteria and the QueryOver provide you just yet another querying mechanism that allows you to pull data out of the database using 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 – Collection Mapping

NHibernate – Collection Mapping ”; Previous Next In this chapter, we will be covering how to represent collections. There are different types of collections that we can use within the NHibernate such as − Lists Sets Bags Now, from the .NET perspective, we generally deal with lists or like very simple data structures, lists, dictionaries. .NET does not have a wide variety of different collection types. So why does NHibernate need all these different types? It really comes back to the database. List A list is an ordered collection of elements that are not necessarily unique. We can map this using the IList <T>. So although we might conventionally have a list of addresses, and from application point of view we know that the elements are unique, nothing in the list prevents us from inserting duplicate elements in that list. Set A set is an unordered collection of unique elements. If you try to insert 2 duplicate elements into a set, it will throw an exception. There”s nothing specific in NHibernate about it. It”s just a convenient way a have a generic set implementation. If you”re on .NET 4, you can use the new HashSet <T> to represent these, but in most NHibernate applications, we represent this is an ISet. It is an unordered, if you pull back a list of addresses from a database or a list of orders, you don”t know what order they”re coming in unless you put in a specific Order by clause. So in general, the data that you”re pulling back from a database are sets. They are unique collections of elements that are unordered. Bag Another common collection that we will see in the database world is a bag, which is just like a set except it can have duplicate elements. In the .NET world, we represent this by an IList. Sets are probably the most common, but you will see lists and bags as well depending on your application. Let’s have a look into a below customer.hbm.xml file from the last chapter in which Set orders are defined. <?xml version = “1.0” encoding = “utf-8” ?> <hibernate-mapping xmlns = “urn:nhibernate-mapping-2.2” assembly = “NHibernateDemo” namespace = “NHibernateDemo”> <class name = “Customer”> <id name = “Id”> <generator class = “guid.comb”/> </id> <property name = “FirstName”/> <property name = “LastName”/> <property name = “AverageRating”/> <property name = “Points”/> <property name = “HasGoldStatus”/> <property name = “MemberSince” type = “UtcDateTime”/> <property name = “CreditRating” type = “CustomerCreditRatingType”/> <component name = “Address”> <property name = “Street”/> <property name = “City”/> <property name = “Province”/> <property name = “Country”/> </component> <set name = “Orders” table = “`Order`”> <key column = “CustomerId”/> <one-to-many class = “Order”/> </set> </class> </hibernate-mapping> As you can see, we have mapped the orders collection as a set. Remember that a set is an unordered collection of unique elements. Now, if you look at the Customer class, you will see that Orders property is defined with an ISet as shown in the following program. public virtual ISet<Order> Orders { get; set; } Now when this application is run, you will see the following output. New Customer: John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Order Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6 Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7 The orders were ordered by: John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6 Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7 John Doe (1f248133-b50a-4ad7-9915-a5b8017d0ff1) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: c41af8f2-7124-42a7-91c5-a5b8017d0ff6 Order Id: 657f6bb0-1f42-45fc-8fc7-a5b8017d0ff7 Press <ENTER> to exit… If the items in the collection didn”t need to be unique, if you could have multiple orders with the same primary key occurring multiple times in this collection, then this would be better mapped as a bag as shown in the following program. <bag name = “Orders” table = “`Order`”> <key column = “CustomerId”/> <one-to-many class = “Order”/> </bag> Now, if you run this application you will get an exception because if we take a look at the customer class, you”ll notice that the orders are marked as an ISet in the C# code. So we will also need to change this to an IList and then here, we would need to change from the HashSet to a List in the constructor. public class Customer { public Customer() { MemberSince = DateTime.UtcNow; Orders = new List<Order>(); } public virtual Guid Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual double AverageRating { get; set; } public virtual int Points { get; set; } public virtual bool HasGoldStatus { get; set; } public virtual DateTime MemberSince { get; set; } public virtual CustomerCreditRating CreditRating { get; set; } public virtual Location Address { get; set; } public virtual IList<Order> Orders { get; set; } public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; } public override string ToString() { var result = new StringBuilder(); result.AppendFormat(“{1} {2} ({0})rntPoints: {3}rntHasGoldStatus: {4}rntMemberSince: {5} ({7})rntCreditRating: {6}rntAverageRating: {8}rn”, Id, FirstName, LastName, Points, HasGoldStatus, MemberSince, CreditRating, MemberSince.Kind, AverageRating); result.AppendLine(“tOrders:”); foreach(var order in Orders) { result.AppendLine(“tt” + order); } return result.ToString(); } } When you run the application, you will see the same behavior. But, now we can have an order occurring multiple times in the same collection. John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Order Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286 Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287 The orders were ordered by: John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: 6dd7dbdb-354f-4c82-9c39-a5b8017c3286 Order Id: 9b3e2441-a81b-404d-9aed-a5b8017c3287 John Doe (fbde48f5-d620-4d1c-9a7f-a5b8017c3280) Points:

NHibernate – Cascades

NHibernate – Cascades ”; Previous Next In this chapter, we will be covering how to use the Cascade feature. If you have a set or a collection of items or a relationship between two classes such as our customer and order and have a foreign key relationship. If we delete the customer by default, NHibernate doesn”t do anything to the child objects, so the ones that belong to that customer and we could be orphaning orders. We could also be violating foreign key constraints, so we can use the notion of cascades. By default, NHibernate does not cascade operations to child objects. The reason for this is that you can have relationships such as a customer having a default shipping address and that shipping address is shared with many different customers. So you wouldn”t want to cascade that relationship necessarily because other customers are still referring to it. So the whole notion of cascades is to tell NHibernate how to handle its child entities. There are different options for cascading, which are as follows − none − which is the default and it means no cascading. all − which is going to cascade saves, updates, and deletes. save-update − it will cascade, saves and updates. delete − it will cascade deletes. all-delete-orphan − it is a special one which is quite frequently used and is the same as All Except, if it finds Delete-orphan rows, it will delete those as well. You can specify the default in your hbm.xml file, so you can provide a default cascade on that Hibernate mapping element or you can also specify it for specific collections and relationships such as the many-to-one. Let’s have a look into simple example cascades, let”s fix the problem in the program, where we have to manually cascade the save to the orders as shown in the following code. using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine(“New Customer:”); Console.WriteLine(newCustomer); session.Save(newCustomer); foreach (var order in newCustomer.Orders) { session.Save(order); } id = newCustomer.Id; tx.Commit(); } In the above code snippet, you can see that we are manually saving all the orders for the customer. Now let’s remove manual cascade code in which all the orders are saved. using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine(“New Customer:”); Console.WriteLine(newCustomer); session.Save(newCustomer); id = newCustomer.Id; tx.Commit(); } We need to specify the cascade option in customer.hbm.xml. <?xml version = “1.0” encoding = “utf-8” ?> <hibernate-mapping xmlns = “urn:nhibernate-mapping-2.2” assembly = “NHibernateDemo” namespace = “NHibernateDemo”> <class name = “Customer”> <id name = “Id”> <generator class = “guid.comb”/> </id> <property name = “FirstName”/> <property name = “LastName”/> <property name = “AverageRating”/> <property name = “Points”/> <property name = “HasGoldStatus”/> <property name = “MemberSince” type = “UtcDateTime”/> <property name = “CreditRating” type = “CustomerCreditRatingType”/> <component name = “Address”> <property name = “Street”/> <property name = “City”/> <property name = “Province”/> <property name = “Country”/> </component> <set name = “Orders” table = “`Order`” cascade = “all-delete-orphan”> <key column = “CustomerId”/> <one-to-many class = “Order”/> </set> </class> </hibernate-mapping> Now, orders fully belong to the customer. So if the customers were deleted from the database, our application here would want to delete all of those orders, including any that might have been orphaned. It will end up doing a delete. By that, it will say delete from order table, where the customer ID equals the customer that you”re deleting. So you can actually cascade these deletes. So with the All, it will do saves, updates, and deletes. Now when you run this application, you will see the following output. New Customer: John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Order Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133 Order Id: b03858e7-8c36-4555-8878-a5bb00b85134 The orders were ordered by: John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133 Order Id: b03858e7-8c36-4555-8878-a5bb00b85134 John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133 Order Id: b03858e7-8c36-4555-8878-a5bb00b85134 Press <ENTER> to exit… As you can see that we have deleted the code from the program that manually cascaded and our application is still working. So depending on your relationship, you might want to cascade those. Now, let”s take a look at a different cascade relationship. Let’s go to the Order.hbm.xml file and we can cascade that many-to-one relationship. <?xml version = “1.0” encoding = “utf-8” ?> <hibernate-mapping xmlns = “urn:nhibernate-mapping-2.2” assembly = “NHibernateDemo” namespace = “NHibernateDemo”> <class name = “Order” table = “`Order`”> <id name = “Id”> <generator class = “guid.comb”/> </id> <property name = “Ordered”/> <property name = “Shipped”/> <component name = “ShipTo”> <property name = “Street”/> <property name = “City”/> <property name = “Province”/> <property name = “Country”/> </component> <many-to-one name = “Customer” column = “CustomerId” cascade = “save-update”/> </class> </hibernate-mapping> So if we create a new order and there”s a new customer attached to it and we say, save that order, we might want to cascade that. But one thing that we”d probably don”t want to do is if an order is deleted to delete the corresponding customer. So here, we would want to do a save update, so using a save-update, it will cascade any saves or updates to that customer. So, if we get a new customer or if we are changing the customer, it will cascade that. If it is a delete, it won”t delete that from the database. So running our application again, everything still works as expected. New Customer: John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (10b2a3d7-7fcf-483c-b1da-a5bb00b8512e) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: e6680e30-5b3b-4efa-b017-a5bb00b85133 Order Id: b03858e7-8c36-4555-8878-a5bb00b85134 The orders

NHibernate – Query Language

NHibernate – Hibernate Query Language ”; Previous Next In this chapter, we will be covering Hibernate Query Language. HQL is shared across both Java”s Hibernate and NHibernate. It is the oldest query mechanism along with Criteria. It was implemented very early and it is a string-based query API. You access it through ISession CreateQuery, and it is almost similar to SQL. It uses many of the same keywords, but has a simplified syntax. It is one of the most common examples, if you”re looking for how to perform a query you”ll often find HQL examples. The following is a simple example of HQL − var customers = session.CreateQuery(“select c from Customer c where c.FirstName = ”Laverne””); So here you can see that they select C from customer, it looks a lot like SQL. This is an opaque string as far as NHibernate is concerned, so you don”t know whether this is a valid HQL until runtime, which is one of the disadvantages. One of the strengths of the LINQ provider is you can get to compile time support. But HQL, is one of the most flexible query mechanisms oftenly used. It is said that, if there”s no other way to do it then there”s a way to do it in HQL. Let’s have a look into a simpe example in which we will recreate our LINQ queries using HQL instead. You can get access to HQL by calling the session.CreateQuery and pass as a parameter using an HQL string. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.CreateQuery(“select c from Customer c where c.FirstName = ”Laverne””); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } This HQL string looks a lot like SQL, the main difference is that FirstName is the property name and not the column name. So, if there”s a discrepancy between the two, you use the property name. Same thing, it looks like a table name, but it”s actually the name of the class that we are selecting from. If the back end table was named as Customers, we would still use Customer in our HQL query. Let’s run this application and you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit… Let’s have a look into another simple example in which we will retrieve all those customers whose FirstName starts with the letter H using HQL. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.CreateQuery(“select c from Customer c where c.FirstName like ”H%””); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine(“Press <ENTER> to exit…”); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = “default”; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Let’s run your application again and you will see that all of the customers whose name starts with H are returned from this query. Herman Crooks (4ead3480-6bce-11e1-b15c-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 12/3/2010 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ead3480-6bce-11e1-b15d-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15e-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15f-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b160-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b161-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b162-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b163-6cf049ee52be Hudson Bins (4ec03f80-6bce-11e1-b2b7-6cf049ee52be) Points: 56 HasGoldStatus: False MemberSince: 10/20/2008 12:00:00 AM (Utc) CreditRating: Terrible AverageRating: 0 Orders: Order Id: 4ec03f80-6bce-11e1-b2b8-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2b9-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2ba-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bb-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bc-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bd-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2be-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bf-6cf049ee52be Hettie Feest (4ec50240-6bce-11e1-b300-6cf049ee52be) Points: 82 HasGoldStatus: False MemberSince: 4/10/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ec50240-6bce-11e1-b301-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b302-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b303-6cf049ee52be Press <ENTER> to exit… We can do more complicated things like wanting all orders where customers with an order count is greater than 9. Following is the HQL query for the same. var customers = session.CreateQuery(“select c from Customer c where size(c.Orders) > 9”); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } We also need to indicate that we need a size here or count or length. In HQL, we have the option of using the special size method as shown above. The other way to write this, if you prefer is c.Orders.size, and this has the exact effect. var customers = session.CreateQuery(“select c from Customer c where c.Orders.size > 9″); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } Let”s run this application. Lindsay Towne (4ea3aef6-6bce-11e1-b0cb-6cf049ee52be) Points: 50 HasGoldStatus: False MemberSince: 4/13/2007 12:00:00 AM (Utc) CreditRating: VeryGood AverageRating: 0 Orders: Order Id: 4ea3aef6-6bce-11e1-b0cc-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0cd-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0ce-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0cf-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d0-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d1-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d2-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d3-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d4-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d5-6cf049ee52be Wyman Hammes (4ea61056-6bce-11e1-b0e2-6cf049ee52be) Points: 32 HasGoldStatus: False MemberSince: 2/5/2011 12:00:00 AM (Utc) CreditRating: Good AverageRating: 0 Orders: Order Id: 4ea61056-6bce-11e1-b0e3-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e4-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e5-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e6-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e7-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e8-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e9-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0ea-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0eb-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0ec-6cf049ee52be Press <ENTER> to exit… You can see that all the customers, who have more than 9 orders are retrieved from the database. Print Page