Sie sind auf Seite 1von 9

An Example of using

NHibernate with .NET

Gemunu R. Wickremasinghe
Change Log

Version Date Initials Remarks


th
0.5 16 Aug 2005 GW Draft
th
1.0 17 Aug 2005 GW Added introduction section (as suggested by CM).
Expanded n-Tier Architecture to include Data Access
Layer. Included Notes under sections 2.1.4.1.2 and
2.1.4.1.4 to suggest alternate approaches to replace XML
mapping documents
th
1.5 18 Aug 2005 GW General fresh up
th
1.6 24 Aug 2005 GW Addressing review concerns
st
1.7 31 Aug 2005 GW Added whitepaper content to introduction
st
1.8 01 Sep 2005 GW Finishing touch

Table of Contents

1 Introduction ....................................................................................................................................................... 3
1.1 What is NHibernate?................................................................................................................................... 3
1.2 What problems does it solve?..................................................................................................................... 3
1.3 Other similar frameworks ............................................................................................................................ 3
1.4 History of NHibernate.................................................................................................................................. 3
2 Example Application......................................................................................................................................... 4
3 User Interface .................................................................................................................................................... 4
3.1 Main Window .............................................................................................................................................. 4
3.1.1 Actions ................................................................................................................................................ 4
3.2 Orders form................................................................................................................................................. 5
3.2.1 Field Definitions .................................................................................................................................. 5
3.2.2 Actions ................................................................................................................................................ 5
4 Architecture and design................................................................................................................................... 5
4.1 Application Architecture .............................................................................................................................. 6
4.1.1 Database............................................................................................................................................. 6
4.1.2 NHibernate .......................................................................................................................................... 7
4.1.3 log4net ................................................................................................................................................ 7
4.1.4 Data Access Layer .............................................................................................................................. 7
4.1.4.1 DataAccessLayer.Beans namespace............................................................................................. 7
4.1.4.1.1 Customer class......................................................................................................................... 7
4.1.4.1.2 The XML mapping for Customer class (Customer.hbm.xml) ................................................... 7
4.1.4.1.3 Order class ............................................................................................................................... 8
4.1.4.1.4 The XML mapping for Order class (Order.hbm.xml) ................................................................ 8
4.1.4.2 DataAccessLayer.Services namespace ......................................................................................... 9
4.1.4.2.1 DataService class..................................................................................................................... 9
4.1.4.3 BusinessLogicLayer.Services namespace ..................................................................................... 9
4.1.4.3.1 OrderService class ................................................................................................................... 9
4.1.5 UI layer................................................................................................................................................ 9

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 2 of 9


1 Introduction
The need to deal with relational data is something that arises almost always with business applications. The
implementation of data access layer has been drawing attention of everyone so often due to the above reason. It
is not the mere implementation of the data access layer that cost a lot in a software project but the direct and side
effects of wrong approaches when doing so. Finding the most cost effective approach for handling data access
requirements have been the focus of many researchers including some open source groups.

Object relational mapping (O/R mapping) is recognized as a concept that can solve most of the well known issues
faced by developers related to data access. This concept links object oriented programming with relational data
models. O/R mapping can establish a bidirectional mapping between the data in a relational database and Objects
in code.

1.1 What is NHibernate?


NHibernate is an open source framework that implements the Object relational mapping concept for .NET
developments. This framework covers about 95 percent of common data persistence related programming tasks
while allowing the result set translation from tabular representation to graph of objects.

1.2 What problems does it solve?


The plain data access implementation using ADO.NET involves a lot of tedious, repetitive work, which consumes a
lot of the time from the application developers. Such an approach can also make it so hard to separate data
access implementation from the business logic or presentation layer implementations. Difficulty to reach n-tier
architecture for application development can fire back at later stages of projects with unmanageable costs.
NHibernate framework helps solving the above issues while integrating Object oriented programming with
relational databases.

1.3 Other similar frameworks


The choice of the O/R mappers for the .NET developers is immense. Following URLs contain such listings posted
by the sites interested in the subject.

http://www.theserverside.net/news/thread.tss?thread_id=29914

http://sharptoolbox.com/Category74089b0a-1105-4389-b1db-eedf27e20cfb.aspx

1.4 History of NHibernate


Just like the Java environment inspired the core languages and concepts within .NET environment, the roots of
NHibernate lie in the Java world. In other words NHibernate is a port of the Java Hibernate relational persistence
framework. You can read more about NHibernate from the official documentation link at

http://nhibernate.sourceforge.net/nh-docs/en/html/chunk/index.html

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 3 of 9


2 Example Application
In order to help the growing popularity of the usage of NHibernate framework, I decided to go ahead and
implement a simple real world application while trying to focus a lot on an n-Tier approach that plays a vital role in
enterprise application developments and maintenance.

This sample application is implemented to pick a customer from an available collection in a backend data table
and then retrieves the orders placed by any selected customer in a child data table. This application also allows
inserting new orders to the current collection under the same customer and editing any order through the UI. The
application is not made extra complex in order to leave room for the easy grasp of the concepts covered.
Following is how the NHibernate framework is used inside the application to get the job done.

The usage of NHibernate framework is cleanly restricted to MiddleTiers.dll assembly that implements both “Data
access layer” and the “Business logic layer” of the sample. The NHibernate framework initialization code is
implemented as the sole representative of data access logic which is the “DataService” class. That logic is called
only once for the application lifetime to initialize the open source frameworks as declared in application
configuration (app.config) file under <nhibernate></nhibernate> and <log4net></ log4net > sections. The business
logic layer simply uses this class and appropriate persistence classes available in “DataAccessLayer.Beans” sub
namespace to support the requirements from the UI. The UI layer does not worry about the internal
implementation details of any API and simply invokes the relevant methods of classes available in
“BusinessLogicLayer.Services” namespace to get the expected results out.

The rest of this document explains the UI, architecture and design of the sample in more details

3 User Interface
3.1 Main Window

Figure 1: Main Window

3.1.1 Actions
Action Elements Action
Select customers combo box Click on the drop down button will show the list of customers available so
that user can scroll down to select the desired customer.
View Orders This will invoke the Orders window (modal) populated with orders
corresponding to the selected customer (Refer section 2.2)
1
Cancel Click on the “Cancel” button will quit the application

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 4 of 9


3.2 Orders form

Figure 2: Orders Form

3.2.1 Field Definitions


Item Default
Orders from the customer Populated with the customer selection of the main form
Orders Data grid Populated with the orders from the selected customer

3.2.2 Actions
Action Elements Action
Insert an Order This will append a dummy order record to the current list of orders from the
customer and commit changes to the backend
Update User can do changes to the grid cells and click on this button to commit
changes to the backend.
Cancel Close the Orders form allowing access to Main form

4 Architecture and design


This chapter provides the overview/design descriptions in terms of the following;

• Database – The backend details of this sample


• NHibernate – Open source ORM framework
• Log4Net – Open source logging framework
• DataAccessLayer/BusinessLogicLayer – Middle tiers.
• UI Layer

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 5 of 9


4.1 Application Architecture

Presentation Layer
App.config file MainForm OrdersForm
-nHibernate
-log4net

Business Logic Layer


OrderService
(BusinessLogicLayer.Services)
log4net

Data Access Layer


Persistent Objects DataService
(DataAccessLayer.Beans) (DataAccessLayer.Services)

NHibernate
Session SessionFactory ADO.NET

Database

Figure 3: Application architecture

4.1.1 Database
SQL 2000 server installation includes the installation of a pre-populated DB called Northwind. The following two
tables from this DB is used as the data model for the application

Figure 4: Data Model

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 6 of 9


4.1.2 NHibernate
This is the Open source framework used for the Object Relational Mapping and focus of this sample application.
The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object
model to a relational data model with a SQL-based schema.

4.1.3 log4net
This is an Open source framework for extending the error logging implementations of applications to output log
statements to a variety of output targets without adding substantial performance overheads. The official link for this
framework is http://www.neoworks.com/products/free/log4net/ .

N.B. Both this framework and NHibernate are to be configured through different sections in configuration file. Once
these frameworks are embedded in the middle tiers, they should be able to be configured based on the
requirements of the users of the middle tiers. through the app.config file of the application.

4.1.4 Data Access Layer


This is the part of the middle tier that uses NHibernate open source framework for implementing the data access
needs to cater to the Business Logic layer. This includes two sub namespaces as follows.

4.1.4.1 DataAccessLayer.Beans namespace

This namespace is used for accumulating the .NET persistent class declarations corresponding to each backend
table accessed by the application. The XML mapping documents based on each .NET persistent class is also kept
here. When declaring the persistent class for a table, we can include only the columns required by the application
to the class declarations while excluding all unwanted columns. Customer is such a class that includes only two
columns out of 11 columns in the actual backend table (Customers table in figure 4)

4.1.4.1.1 Customer class

Customer

private string companyName


private string customerId

public string CompanyName


public string CustomerID

Figure 5: Customer persistent class

4.1.4.1.2 The XML mapping for Customer class (Customer.hbm.xml)

<?xml version="1.0" encoding="utf-8" ?>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"
namespace="DataAccessLayer.Beans" assembly="MiddleTiers">
<class name="Customer" table="Customers">
<id name="CustomerID">
<generator class="assigned" />
</id>
<property name="CompanyName"/>
</class>
</hibernate-mapping>

N.B. If you feel like the creation and maintenance of the XML mapping document is a hassle,
NHibernate.Mapping.Attributes available in NHibernateContrib has a very good alternate for getting rid of the

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 7 of 9


above file altogether through attribute programming. The details and instructions for implementation is available at
the link published by me at http://sourceforge.net/forum/message.php?msg_id=3233643

4.1.4.1.3 Order class

Order

private int orderId;


private string customerId;
private int employeeId;
private DateTime orderDate;
private DateTime requiredDate;
private DateTime shippedDate;
private int shipVia;
private double freight;
private string shipName, shipAddress, shipCity,
shipRegion, shipPostalCode, shipCountry;

public int OrderID


public string CustomerID
public int EmployeeID
public DateTime OrderDate
public DateTime RequiredDate
public DateTime ShippedDate
public int ShipVia
public double Freight
public string ShipName
public string ShipAddress
public string ShipCity
public string ShipRegion
public string ShipPostalCode
public string ShipCountry

Figure 6: Order persistent class

4.1.4.1.4 The XML mapping for Order class (Order.hbm.xml)

<?xml version="1.0" encoding="utf-8" ?>


<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"
namespace="DataAccessLayer.Beans" assembly="MiddleTiers">
<class name="Order" table="Orders">
<id name="OrderID" > <generator class="identity" /></id>
<property name="CustomerID" />
<property name="EmployeeID"/>
<property name="OrderDate" />
<property name="RequiredDate"/>
<property name="ShippedDate" />
<property name="ShipVia"/>
<property name="Freight"/>
<property name="ShipName"/>
<property name="ShipAddress"/>
<property name="ShipCity"/>
<property name="ShipRegion"/>
<property name="ShipPostalCode"/>
<property name="ShipCountry"/>

</class>
</hibernate-mapping>

N.B. XML mapping can be avoided in the same way as described under the Customer class description.

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 8 of 9


4.1.4.2 DataAccessLayer.Services namespace

This namespace has two classes. The DataService class implements the code required for initializing open source
frameworks in runtime and the code useful in using the features of frameworks.

4.1.4.2.1 DataService class

DataService
public void Initiate()
public void Dispose()

private static ILog log


private static Configuration nHibernateConfig;
private static ISessionFactory nHibernateFactory;

public ISession NHibernateSession

Figure 7: DataService class

The Initiate() method of the class should be called only once at application start up and the property
NHibernateSession can be used to accomplish any data access need including transactional processing. Some of
such implementations are included in OrderService class (section 3.1.4.3.1) mentioned below.

4.1.4.3 BusinessLogicLayer.Services namespace

The OrderService class is the one that supports all the specific data access needs of both MainForm and
OrdersForm. There could be new classes in this namespace to cater to different applications or different features
of the same application when there are needs for more data access scenarios in the future.

4.1.4.3.1 OrderService class

OrderService
public static IList GetCustomers()
public static IList GetOrdersByCustomerId(string CustomerID)
public static void UpdateOrder(Order order)
public static void InsertOrder (Order order)
private static ILog log

Figure 8: OrderService class


The first two methods of this class are for initializing the MainForm and OrdersForm respectively. The other two
methods are for “Update” and “Insert an Order” button handlers

4.1.5 UI layer
This layer implements only the UI forms in addition to app.config file that declares the NHibernate and log4net
framework configurations. This assembly only refers to the middle tier and does not know usage details of
NHibernate at all. The log4net implementation is also restricted to the middle tier for now. However the decision of
extending it to UI layer to be decided based on the application requirements.

The beauty of this approach could really be seen if there is a need to implement a Web based solution that
provides the same features. Then it would only be the Web forms that need creation and binding to middle tiers.
The entire middle tier could be used seamlessly to cater to the Web UI just like it did for Windows UI. This
eliminates the need for rewriting a whole new application with lot of code duplication just to support a different UI
scenario.

© Copyright CodeConnexion (Pvt.) Ltd. 2005 Page 9 of 9

Das könnte Ihnen auch gefallen