Wednesday, 15 June 2011

Getting Started with NHibernate - Part 2


This post is a continuation of previous post. This post gives a startup using NHibernate framework. In this post we are discussing the Data access components.

In Data Access project, I have created a class CustomerDA for specifying Data Access methods. This class has the following method.

  1. GetConfigFilePath – This method is a Private method, used for getting the physical path of nhibernate.config file located in UI Project.
    /// <summary>
    /// Geting the nhibernate.config file path
    /// </summary>
    private string GetConfigFilePath
    {
        get
        {
            string path = HttpContext.Current.Request.PhysicalApplicationPath;
            if (!path.EndsWith("\\"))
                path = path + "\\";
    
            path = path + "nhibernate.config";
            return path;
        }
    }
  2. Get – Method for getting Customer details for a particular Customer.
    /// <summary>
    /// Get the customer details with Customer Id 
    /// </summary>
    /// <param name="customerID"></param>
    /// <returns></returns>
    public Customer Get(string customerID)
    {
        try
        {
            // Create the configuration object
            Configuration cfg = new Configuration();
            cfg.Configure(GetConfigFilePath);
    
            // Create the session
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
    
            // Open the session
            using (ISession session = sessionFactory.OpenSession())
            {
                // Get Cusomers
                IList<Customer> customers = session.CreateCriteria(typeof(Customer))
                                                .Add(Expression.Eq("CustomerID", customerID))
                                                .List<Customer>();
    
                // Get the first customer (as CustomerID is unique, it will be always one)
                Customer customer = null;
                if ((customers != null) && (customers.Count > 0))
                    customer = customers[0];
    
                return customer;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  3. GetAll – Method for getting all the Customer in a list from the database.
    /// <summary>
    /// Get all the customer from the database.
    /// </summary>
    /// <param name="sortBy"></param>
    /// <param name="sortType"></param>
    /// <returns></returns>
    public IList<Customer> GetAll(string sortBy, SortType sortType)
    {
        try
        {
            // Create the configuration object
            Configuration cfg = new Configuration();
            cfg.Configure(GetConfigFilePath);
    
            // Create the session
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
    
            // Open the session
            using (ISession session = sessionFactory.OpenSession())
            {
                // Create Criteria
                ICriteria criteria = session.CreateCriteria(typeof(Customer));
    
                if (sortBy != null) //If sortBy values pass (Pass null if not required)
                    criteria.AddOrder(sortType == SortType.Ascending ? Order.Asc(sortBy) : Order.Desc(sortBy));
    
                // Get Cusomers
                IList<Customer> customers = criteria.List<Customer>();
    
                return customers;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  4. Create – Method for creating a Customer
    /// <summary>
    /// Create the Customer details
    /// </summary>
    /// <param name="customer"></param>
    public void Create(Customer customer)
    {
        ITransaction transaction = null;
        try
        {
            // Create the configuration object
            Configuration cfg = new Configuration();
            cfg.Configure(GetConfigFilePath);
    
            // Create the session
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
    
            // Open the session
            ISession session = sessionFactory.OpenSession();
    
            // Begin a new ITransaction
            transaction = session.BeginTransaction();
    
            // Save the given entity.
            session.Save(customer);
            session.Flush();
    
            transaction.Commit();
        }
        catch (Exception ex)
        {
            // Rollback the transaction.
            if (transaction != null)
            {
                transaction.Rollback();
            }
            throw ex;
        }
    }
  5. Update – Method for Update an existing Customer.
    /// <summary>
    /// Update the Customer details
    /// </summary>
    /// <param name="customer"></param>
    public void Update(Customer customer)
    {
        ITransaction transaction = null;
        try
        {
            // Create the configuration object
            Configuration cfg = new Configuration();
            cfg.Configure(GetConfigFilePath);
    
            // Create the session
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
    
            // Open the session
            ISession session = sessionFactory.OpenSession();
    
            // Begin a new ITransaction
            transaction = session.BeginTransaction();
    
            // Get existing Cusomer
            Customer existingCustomer = session.Get<Customer>(customer.CustomerID);
            if (existingCustomer == null)
                throw new Exception(string.Format("Can not find the Customer with id: {0}.", customer.CustomerID));
            session.Clear();
            // Save the given entity.
            session.Update(customer);
            session.Flush();
    
            transaction.Commit();
        }
        catch (Exception ex)
        {
            // Rollback the transaction.
            if (transaction != null)
            {
                transaction.Rollback();
            }
            throw ex;
        }
    }
  6. Delete – Method for Deleting an Existing Customer. Here I can call this method using Customer Id or Customer object from UI layer.
    /// <summary>
    /// Delete the Customer details
    /// </summary>
    /// <param name="customer"></param>
    public void Delete(Customer customer)
    {
        ITransaction transaction = null;
        try
        {
            // Create the configuration object
            Configuration cfg = new Configuration();
            cfg.Configure(GetConfigFilePath);
    
            // Create the session
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
    
            // Open the session
            ISession session = sessionFactory.OpenSession();
    
            // Begin a new ITransaction
            transaction = session.BeginTransaction();
    
            // Get existing Cusomer
            Customer existingCustomer = session.Get<Customer>(customer.CustomerID);
            if (existingCustomer == null)
                throw new Exception(string.Format("Can not find the Customer with id: {0}.", customer.CustomerID));
    
            // To clean the session, because we just use the 'session.Get' method.
            session.Clear();
    
            // Delete the given entity.
            session.Delete(customer);
            session.Flush();
    
            transaction.Commit();
        }
        catch (Exception ex)
        {
            // Rollback the transaction.
            if (transaction != null)
            {
                transaction.Rollback();
            }
            throw ex;
        }
    }
    /// <summary>
    /// Delete the Custoer Details
    /// </summary>
    /// <param name="customerID"></param>
    public void Delete(string customerID)
    {
        Customer customer = Get(customerID);
        Delete(customer);
    }
  7. I also have an enum which is used in GetAll method for specifying the sorting type.
    public enum SortType
    {
        Ascending,
    
        Descending
    }

The output of the running sample looks below:
Entry Screen for Customer (using NHibernate framework)

download the working example of the source code in C# here


2 Responses to “Getting Started with NHibernate - Part 2”

  • deepzb84 says:
    5 February 2012 at 10:12

    HI thanks for this nice post...but can you post some with parent and child relationship table ...CRUD....

  • Thirumalai M says:
    5 February 2012 at 12:14

    Hi deepzb84, Thanks for your comments. Could you please send me some more information about your requirement to understand better. So I can provide a sample implementation for the same.

Post a Comment