Using NHibernate in MVC

Source: Internet
Author: User

NHibernate is a. Net based, The object persistence Class library for the relational database. It is the famous hibernate. NET version, NHibernate is used to persist your. NET objects into the underlying relational database. You don't have to write your own SQL statements to manipulate these objects at all. NH will do it for you. You only need to care about these objects in your code, NH generates SQL statements and gets you the right things. When using NHibernate, you can use any database, just configure it as the corresponding database driver when configuring Nhiternte.

First, the preparatory work:

1. Create the in database. NET class persisted table.
2, create the need to be persisted. NET class.
3. Create a mapping file to tell NH how to persist the properties of these classes.
4. Create a NH configuration file to tell NH how to connect to the database.

Step 1: Create a database table
In this instance I am using the MySQL database, the database name is CMS, the table name is member, and the table statement:

CREATE TABLE member (Idintauto_increment primary KEY,Account varchar ( -) notNULLComment'Account', ' Password ' varchar ( -) notNULLComment'Password', ' Type 'int default 0NotNULLComment'Type: 0, ordinary member', ' Source 'int default 0NotNULLComment'Source: 0, General registration; 1 Other registrations', freezedint default 0NotNULLComment'Status: 0, normal; 1, disable', ' datetime ' datetime notNULLComment'Registration Time') Comment'website Members';

Step 2: Create. NET class:

NH works by reflection object properties, so we add properties to objects that need to be persisted. A class that corresponds to the database structure above can be written like this:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceCMS. data.domainmodels{ Public classMember { Public Virtual intId {Get;Set; } Public Virtual stringAccount {Get;Set; }  Public Virtual stringPassword {Get;Set; }  Public Virtual intType {Get;Set; }  Public Virtual intSource {Get;Set; }  Public Virtual intfreezed {Get;Set; }  Public Virtualdatetime datetime {Get;Set; } }}

Step 3: Write the mapping file (Mapping files)
Now we have the database tables and. NET class, we also need to tell NH how to map between the database and the class. This requires a mapping file. The simplest (and most maintainable) method is to write a mapping file for each class, and if you put a mapping file named "XXX.hbm.xml" in the same directory as the XXX class file, NH will make everything very easy. Here, our Member.hbm.xml may look like this:

<?xml version="1.0"encoding="Utf-8"? >"urn:nhibernate-mapping-2.2"> <className="CMS. Data.DomainModels.Member, CMS. Data"table="Member"> <id name="Id"column="ID"> <generatorclass="native"/> </id> <property name =" Account"column=" Account"/> <property name ="Password"column="Password"/> <property name ="Type"column="Type"/> <property name ="Source"column="Source"/> <property name ="freezed"column="freezed"/> <property name ="DateTime"column="DateTime"/> </class>

Here's an explanation of the mapping file:

The first tag is class, where we map the type name (class name and assembly name) to the member table in the database (this is a bit different from hibernate and we have to tell NH where this class came from.) This difference is made by. NET and Java Reflect mechanisms). In this case, we are loading the CMS.Data.DomainModels.Member class from the CMS.Data.DomainModels. NH adheres to. Net The Framework uses reflection to load the type of rules-so if you're having any doubts, check the. NET Framework SDK. Let's skip the "ID" tag for a moment and say the property node first. " Name "Property value is what we write. NET class, the Column property value is the field name that corresponds to the ' Net class ' attribute in the database. The type attribute is optional (if you do not indicate that NH will give the best fit), but the recommended practice is to take this attribute. Hibernate users will notice that In the value of the type attribute, we give the length value, because this is what ADO needs to do. Let's go back to "id" tag, you might guess this tag is related to the primary key mapped to the table. Correct. ID tag format and property tag is similar. We map from the property (name) to the field (Colume) of the target database. These embedded generator tags tell nh how to generate primary Key (NH is very handy to generate one, no matter what type, As long as you tell it how to do it).

Note: After you complete the mapping file, you want to change the properties of the map file, property, and build operation to an embedded resource.

Step 4: Create a Database configuration file
So far, we haven't told NH where to find the database. The most straightforward approach is to give the NH a section in your program's configuration file, which is:

<!--nhibernate Configuration starts--<configSections> <section name="hibernate-configuration"Type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/> </configSections> "urn:nhibernate-configuration-2.2"> <session-factory name="nhibernatesession"> <property name="Connection.driver_class">NHibernate.Driver.MySqlDataDriver</property> <property name="Connection.connection_string_name">ConnectionString</property> <property name="Show_sql">true</property> <property name="dialect">NHibernate.Dialect.MySQLDialect</property> <property name="Cache.use_second_level_cache">false</property> <property name="Cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property> <property name="Generate_statistics">true</property> <property name="cache.default_expiration"> -</property> <property name="Cache.region_prefix">CMS</property> <mapping assembly="CMS. Data"/> </session-factory> 

The above example uses the MySQL driver to connect to the local database link named ConnectionString on the database, the mapped file under the Cms.data folder.

After completing the above four steps, you will have the following outcome documents:

1. A database table called member.

2, Member.cs-need to be persistent. NET class.

3, Member.hbm.xml-map file.

4. Web. config-configuration information with NHibernate connection information (you can also specify in the code)

Second, start experiencing nhibernate:

Using NHibernate in your code is a simple matter and requires the following steps:
1. Create a Sessionfactory object.

2. Create a session to connect to the set database.

3, below you can make the query save operation

Step one, create a Sessionfactory object
When creating sessionfactory in one of the controllers in your new MVC site, be careful to introduce the following two references:

using NHibernate; using Nhibernate.cfg;

Create the following statement:

New Configuration (). Configure (). Buildsessionfactory ();

Step two, create a Session object
The ISession object represents a connection to a back-end database, and ITransaction represents a NHibernate-managed transaction (Transaction).

= Sessionfactory. Opensession ();
= Session. BeginTransaction ();

Step three, the application of various operations, you can now treat these objects in. NET manner

If you want to save a new member in the database, you only need to

if(Session! =NULL)            {                varModel =NewCMS.                Data.DomainModels.Member (); Model. Account="CMS"; Model. Password="123456"; Model. Type=0; Model. Source=0; Model. Freezed=0; Model. DateTime=System.DateTime.Now; Session.                Save (model);                Transaction.commit (); Session.            Close (); }

The overall controller code is as follows:

 PublicActionResult Index () {isessionfactory sessionfactory=NewConfiguration (). Configure ().            Buildsessionfactory (); ISession Session=sessionfactory.opensession (); ITransaction Transaction=session.            BeginTransaction (); if(Session! =NULL)            {                varModel =NewCMS.                Data.DomainModels.Member (); Model. Account="CMS"; Model. Password="123456"; Model. Type=0; Model. Source=0; Model. Freezed=0; Model. DateTime=System.DateTime.Now; Session.                Save (model);                Transaction.commit (); Session.            Close (); }            returnContent ("Registration Successful"); }

Results after the run:

At this point, you will see the data that you just registered on the database surface:

In the run time may be a variety of error messages, general error information directly on the Internet search can find solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.