Basic tutorial and simple encapsulation of nhib.pdf
1. Introduction to nhib Nhibernate is an object/Relational Database ing tool for. NET environments. The term object/relational ing (ORM) represents a technology, it is used to map the Objects represented by the object model to the SQL-based relational model data structure. Simply put, the database structure is directly mapped to the entity model to simplify the SQL data processing time. You can use XML (Fluent) to define data model persistence. The nhing structure inside nhib.pdf and 1-1 are shown as follows: 2. Prepare the nhib.pdf class library and download the train. The source code and examples of the downloaded version of the compressed package. Configure the smart prompt for nhib.pdf configuration of Visual Studio, and find the configuration from the previous download package. xsd and nhibernate-mapping.xsd placement X: \ Program Files \ Microsoft Visual Studio X \ Xml \ SchemasNorthwind database (Sample Database) can also enable other databases to create a NhibernateTest solution, directory structure 1-23. Use the example nhib.pdf through the configuration file (app. config, web. config, db. cfg. xml) to obtain the ISessionFactory. Generally, a database maintains an ISessionFactory. The ISessionFactory factory creates an ISession (nhibsion ). ISession indicates a database operation, which must be closed after an operation. SessionFactory (nhib.pdf. ISessionFactory) is a thread-safe and immutable cache snapshot for compiled ing files of a single database. It is a Session factory and a ConnectionProvider customer. You can hold an optional (second-level) data cache and store data that can be reused in transactions at the process or cluster level. Session, Session (nhib.pdf. ISession) single thread, short-lived objects, representing a dialogue between the application and the persistence layer. Encapsulates An ADO. NET connection. It is also the factory of Transaction. Save the cache of the required (level 1) Persistent object, which is used to traverse the object graph or find the object through the identifier. Now we need to configure the Northwind. cfg. xml database for reading and writing data for the Northwind database's MERs table.
<?xml version="1.0" encoding="utf-8" ?>
Customers ing of object objects, including object objects and corresponding ing xml. Note that the id column of object ing is required. Otherwise, an error is reported. Generally, set three types in the configuration file: native (select one of identity, sequence, or hilo Based on the capabilities of the underlying database), assigned (specified by yourself ), forign (uses the identifier of another associated object and is used together with <one-to-one>. )
public class Customers:IAggregateRoot { public Customers() { } public virtual string CustomerID { get; set; } public virtual string CompanyName { get; set; } public virtual string ContactName { get; set; } public virtual string ContactTitle { get; set; } public virtual string Address { get; set; } public virtual string City { get; set; } public virtual string Region { get; set; } public virtual string PostalCode { get; set; } public virtual string Country { get; set; } public virtual string Phone { get; set; } public virtual string Fax { get; set; } }
<?xml version="1.0" encoding="utf-8" ?>
Console call to perform basic operations on MERs
// The full address of the Database Configuration File var dbConfigFullPath = System. IO. path. combine (AppDomain. currentDomain. baseDirectory, "Northwind. cfg. xml "); // Hibernate loads the database configuration file var nHConfiguration = new nhib.pdf. cfg. configuration (). configure ("Northwind. cfg. xml "); // obtain the session factory var sessionFactory = nHConfiguration. buildSessionFactory (); using (var session = sessionFactory. openSession () {var customer = new MERs () {CustomerID = "luge", CompanyName = "", Address = "", Phone = "123456 "}; // insert data session. save (customer); session. flush (); // get is used to directly execute an SQL statement to obtain the object var getCustomer = session. get <Customers> ("luge"); getCustomer. companyName = ""; session. saveOrUpdate (getCustomer); session. flush (); // load runs the SQL statement var loadCustomer = session only when it is called. load <Customers> ("luge"); session. delete (loadCustomer); session. flush ();}
Database Table relationship ing (one-to-many, many-to-many) in the Northwind database, the Customers table and the Orders table are one-to-many relationships. The Customers table and the CustomerDemographics table indicate many-to-many relationships. NHibernate ing nodes for the set. (tip: since the author uses the latest version of Nhibernate 4.0.3GA, The Net4.0 ISet <T> interface is supported internally and the Iesi has been removed. collections reference) <set> element: its elements are not stored in sequence and are not repeated. <list> element: it needs to store the location of each element with an additional index column in the database table corresponding to the set attribute. <Bag> element: its elements may be repeated, but they do not save the order. <map> element: its elements are saved as key-value pairs, which is also unordered, its elements can be sorted in the natural order. The xml configuration between MERs and Orders is as follows:
<! -- Customers xml mapping --> <set name = "Orders" generate = "true"> <key column = "CustomerID"/> <one-to-define class = "Orders "/> </set> // Add a mers MERs object // constructor public Customers () {Orders = new HashSet <Orders> ();} public virtual ISet <Orders> Orders {get; set ;}<! -- Orders xml mapping --> <export-to-one name = "Customers" class = "Customers"> <column name = "CustomerID"/> </export-to-one> // Add public virtual MERs {get; to the Orders object; set ;}
// Many-to-many relationship <! -- Customers xml mapping --> <set name = "CustomerDemographics" table = "CustomerCustomerDemo" schema = "dbo" generic = "true"> <key column = "CustomerID"/> <comment -to-define class = "mermerdemographics" fetch = "join" column = "CustomerTypeID"/> </set> // Customers entity, the constructor adds an instance of public virtual ISet <CustomerDemographics> CustomerDemographics {get; set ;}<! -- CustomerDemographics xml mapping --> <set name = "Customers" table = "mermercustomerdemo"> <key column = "CustomerTypeID"/> <allow-to-define class = "Customers" fetch = "join" column = "CustomerID"/> </set> // Add the merdemographics object to instantiate the public virtual ISet <Customers> MERs {get; set ;}
4. Extended nhib.pdf is generally encapsulated for specific projects. The author abstracts an IRepositoryd <T, TEntity> interface as a public interface (the content of this article is just an example. If it is used for specific projects, you can adjust it yourself)
Public interface IRepository <T, EntityKey> where T: IAggregateRoot {void Add (T entity); void Remove (T entity); void Save (T entity ); T FindBy (EntityKey Id); IEnumerable <T> FindAll (int index, int pageSize, out int count ); IEnumerable <T> FindBy (IList <ICriterion> queryList, Order order); IEnumerable <T> FindBy (IList <ICriterion> queryList, Order order, int index, int pageSize, ou T int count);} public abstract class Repository <T, EntityKey>: IRepository <T, EntityKey> where T: IAggregateRoot {private IUnitOfWork _ uow; public Repository (IUnitOfWork uow) {_ uow = uow;} public void Add (T entity) {_ uow. registerNew (entity); // throw new NotImplementedException ();} public void Remove (T entity) {_ uow. registerRemoved (entity); // throw new NotImplementedException ();} public vo Id Save (T entity) {_ uow. registerAmended (entity);} public T FindBy (EntityKey Id) {return _ uow. session. get <T> (Id);} public IEnumerable <T> FindAll () {return (List <T>) _ uow. session. createCriteria (typeof (T )). list ();} public IEnumerable <T> FindAll (int index, int pageSize, out int count) {ICriteria CriteriaQuery = _ uow. session. createCriteria (typeof (T); index = (index> = 1? Index: 1); var countCirteria = CriteriaQuery. clone () as ICriteria; var futureCount = countCirteria. setProjection (Projections. rowCount ()). futureValue <Int32> (); count = futureCount. value; var queryList = CriteriaQuery. setFirstResult (index-1) * pageSize ). setMaxResults (pageSize ). list (); return (List <T>) queryList;} public IEnumerable <T> FindBy (IList <ICriterion> queryList, Order order) {// Restrictions. eq ("Category. id ", 2) Add the query data ICriteria CriteriaQuery = _ uow. session. createCriteria (typeof (T); foreach (var queryItem in queryList) {CriteriaQuery. add (queryItem);} return CriteriaQuery. addOrder (order ). list <T> ();} /// <summary> ///// </summary> /// <param name = "queryList"> </param> /// <param name = "order "> </param> /// <param name =" index "> </param> /// <param name =" count "> </param> // <returns> </r Eturns> public IEnumerable <T> FindBy (IList <ICriterion> queryList, Order order, int index, int pageSize, out int count) {ICriteria CriteriaQuery = _ uow. session. createCriteria (typeof (T); foreach (var queryItem in queryList) {CriteriaQuery. add (queryItem);} var listByQuery = CriteriaQuery; var countCrieriaQuery = CriteriaQuery. clone () as ICriteria; var rowCount = countCrieriaQuery. setProjection (Pr Ojections. RowCount (). FutureValue <Int32> (); count = rowCount. Value; index = index> = 1? Index: 1; return listByQuery. AddOrder (order). SetFirstResult (index-1) * pageSize). SetMaxResults (pageSize). List <T> ();}