Ext.: http://www.cnblogs.com/huhai121/p/3955755.html
NHibernate Application One: Environment preparation
This chapter describes the development and database Tools required for the entire development environment, as well as database design, and subsequent chapters will be expanded with the current database design as an example.
First, the environment configuration:
A, operating system
WIN7 Flagship edition
B. Development environment
VS2010
NHibernate4.0.0
C. Data Environment
PowerDesigner 15.1
SQL Server 2008
Second, the database design:
A, table structure design:
B, build the table statement
1), Customer table
CREATE TABLE CustomerInfo (
CustomerID varchar () NOT NULL,
CustomerName varchar (+) NOT NULL,
Linkphone varchar () NOT NULL,
linkaddress varchar (+) NOT NULL,
Constraint Pk_customerinfo primary KEY (CustomerID)
)
Go
2), Product table
CREATE TABLE ProductInfo (
ProductID varchar () NOT NULL,
ProductName varchar (+) NOT NULL,
Productprice Decimal (18,2) is not NULL,
Constraint Pk_productinfo primary KEY (ProductID)
)
Go
3), order form
CREATE TABLE OrderForm (
Orderformid varchar () NOT NULL,
CustomerID varchar ($) NULL,
Orderformtime datetime NOT NULL,
Constraint Pk_orderform primary KEY (Orderformid)
)
Go
4), Order schedule
CREATE TABLE Orderproduct (
Orderproductid varchar () NOT NULL,
ProductID varchar ($) NULL,
Orderformid varchar ($) NULL,
Constraint Pk_orderproduct primary KEY (Orderproductid)
)
Go
Third, software configuration
To add the ability to write NHibernate configuration file smart hints for Microsoft Visual Studio 2010. Just find configuration.xsd and nhibernate-mapping.xsd two in the downloaded nhibernate.
Files and copy them to the X:\Program Files\Microsoft Visual Studio 9.0\xml\schemas directory.
NHibernate application Two: the first NHibernate program
When the pre-work is ready to be completed, the NHibernate learning process begins, and in the first NHibernate program, an example of a single record of the Customer table by nhibernate based on the customer number is implemented. In this example, we'll follow the instructions in the following sections.
First, structural analysis
1. Layering
Accustomed to layered architectures, the first NHibernate program is layered in the following manner
Description
A.model layer: The model layer is the lowest level, similar to the physical layer in the traditional three layer, for persistence classes and O/R mapping operations.
B.dal layer: Dataaccesslayer layer, higher than the model layer and lower than the app layer, is the data access layer, defining the object's CRUD operations.
C.app Layer: The application layer, the highest level, for interacting with the user.
2. References
Model layer: referencing the Iesi.Collections.dll assembly
Dal layer: References the NHibernate.dll and Iesi.Collections.dll assemblies, referencing the model layer.
App Layer: references the NHibernate.dll and Iesi.Collections.dll assemblies, referencing the model layer and the DAL layer.
Second, model layer
The pocos,plain old CLR Objects (Plain ordinary CLR Objects) model requires a persisted class, or a DTO (data Transfer object) to be programmed by a simple traditional. NET object,
(This is the simplest way to work so far). In NHibernate, POCO accesses data through the property mechanism of. NET, which can be mapped to a database table.
1. Persistence class for customer tables
Create a new class file for the customer object named CustomerEntity.cs
public class customerentity {public virtual string CustomerID {get; set;} Public virtual string CustomerName {get; set;} Public virtual string Linkphone {get; set;} Public virtual string Linkaddress {get; set;} }
Description
A. NHibernate using getter and setter of attributes for persistence
B. Properties can be set to public, internal, protected, protected internal, or private
Attention:
NHibernate uses the proxy feature by default, requiring that the persisted class is not sealed and that its public methods, properties, and events are declared as virtual. Here, the fields in the class are set to virtual, otherwise an exception occurs,
The exception content is as follows:
"Failed:NHibernate.InvalidProxyTypeException:The following types May is not used as Proxies:DomainModel.Entities.Custo Mer:method Get_customerid
Should be Virtual,method Set_customerid should is virtual ".
2. mapping file for customer tables
Create a new XML file for the customer object named Customer.hbm.xml
<?xml version= "1.0" encoding= "Utf-8"? >
Description
A. The default build action for the XML file is "content", which needs to be modified to "embedded Resource" generation, otherwise an exception occurs, as follows:
Unable to locate persister for the entity named ' NHibernateExample01.Model.Entity.CustomerEntity '.
The Persister define the persistence strategy for an entity.
Possible causes:
The mapping for ' NHibernateExample01.Model.Entity.CustomerEntity ' is not a added to the NHibernate configuration
B. In configuration section < Hibernate-mapping>, urn:nhibernate-mapping-2.2 is the namespace of XML, independent of NHibernate DLL version
C. In configuration section
Could not compile the mapping document:NHibernateExample01.Model.Entity.Customer.hbm.xml
D. Configuration section <generator>, native primary key generation method will automatically choose Identity, Sequence, Hilo primary key generation method according to different underlying database adopt different primary key according to different underlying database
The build method. Because Hibernate uses different mapping methods based on the underlying database, it is easy to migrate programs, which can be used if multiple databases are used in a project.
Third, the DAL layer
1. Session Management class
The data flow for the entire nhibernate is as follows:
A Build Isessionfactory properties and mapping files through the Configuration (NHibernate.Cfg.Configuration).
B. Generate session via Isessionfactory. Isessionfactory is thread-safe, and many threads can access it at the same time.
C. Session takes a single-threaded unit operation (data manipulation). The Session is not thread-safe, it represents a single operation with the database, and it needs to be closed after all the work is done.
This shows that isessionfactory is the core of the entire data access, because it is thread-safe, so it can do global objects, will use a singleton pattern to build its management.
public class SessionManager { private isessionfactory _sessionfactory; Public SessionManager () { _sessionfactory = Getsessionfactory (); } Private Isessionfactory getsessionfactory () { return (new Configuration ()). Configure (). Buildsessionfactory (); } Public ISession getsession () { return _sessionfactory.opensession (); } }
2. Data Access Classes
NHibernate data access is done by the session, so the focus of data access is on ISession.
Create a new CustomerDal.cs class on the DAL layer for data access and write a method Getcustomerid to read customer information.
public class Customerdal { private isession _session; Public ISession Session { set { _session = value; } } Public Customerdal (ISession session) { _session = session; } Public customerentity Getcustomerbyid (string CustomerID) { return _session. Get<customerentity> (CustomerID); } }
4. App Layer
1. NHibernate configuration file
<?xml version= "1.0" encoding= "Utf-8"? >
Description
A The default "Copy to Output directory" of the XML file is "Do not copy", which needs to be modified to "always copy", otherwise an exception appears as follows:
Failed:NHibernate.Cfg.HibernateConfigException:An exception occurredduring configuration of persistence layer. ---->
System.IO.FileNotFoundException: Could not find File "Nhibernatesample\dal. Test\bin\debug\hibernate.cfg.xml ""
B The configuration file will vary depending on the nhibernate version of the DLL, requiring a detailed view of the NHibernate DLL's change log.
C The Connection.provider property sets the database connection provider (generally no need to change unless you decide to implement the provider yourself).
D The Connection.driver_class property sets the driver class for the database (the driver class for SQL Server is set here).
E. The Connection.connection_string property is the connection string for the database.
F. The Show_sql property sets whether the SQL statement being executed is displayed in the console at run time (this property is useful when debugging a program).
G Attribute dialect is a NHibernate dialect that allows NHibernate to use the features of some particular database platform.
H. Attribute query.substitutions, replace some phrases in the nhibernate query with SQL phrases (for example, a phrase may be a function or a character).
I. The attribute mapping node sets the mapping file to be used.
2. form file contents
public partial class Form1:form {public Form1 () { InitializeComponent (); Init (); } private void Init () { string CustomerID = "48cbcdfc-1aaa-4a08-9c9b-4578c6f59e8c"; SessionManager _helper = new SessionManager (); ISession _session = _helper. GetSession (); Customerdal _sample = new Customerdal (_session); customerentity entity = _sample. Getcustomerbyid (CustomerID); if (Entity! = null) { txtName.Text = entity. CustomerName; Txtaddress.text = entity. linkaddress; Txtphone.text = entity. Linkphone;}}}
Description
A There is one piece of data in the CustomerInfo table in the database:
CustomerID |
CustomerName |
Linkphone |
Linkaddress |
48cbcdfc-1aaa-4a08-9c9b-4578c6f59e8c |
Huhai |
18618181513 |
Dong Ying Xi Lu, Saihan District, Hohhot City, Inner Mongolia |
B. The results shown are as follows:
NHibernate Getting Started instance