Chapter 4 Nhibernate document translation-Quick Start

Source: Internet
Author: User

Note: nh1.0.1.0 is used in this article. The configurations of other versions may be slightly different.

Download sample code.

Database script download

I. Architecture

First, let's take a look at the architecture of nhib.pdf:

Nhibent is the persistence layer between databases and applications. Applications and nhibent are linked through persistence objects. Nhib.pdf uses app. config or web. config and the ing file for settings.

The following describes how to use a minimum subset of the nhib.pdf API.

The following are some object definitions in the figure:

Configuration (nhib.pdf. cfg. configuration)

Configuration object used to specify the attributes and ing files used to create isessionfactory. (This object is not shown in the figure)
Sessionfactory (nhib.pdf. isessionfactory)

Session factory.

Session, Session (nhib.pdf. isession)

Represents a conversation 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.

Transaction (nhib.pdf. itransaction)

(Optional) Single-threaded, short-lived object. The application uses it to represent atomic operations of a batch of jobs. Is the abstraction of the underlying ADO. net transaction. A session may span multiple transaction transactions in some cases.

 

Ii. Sample Code

Let's see how they work collaboratively. Please refer to the following code.

Sample Code (query operation without changing the data in the database ):

// Configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // open isessionisession session = factory. opensession (); Session = factory. opensession (); try {Add operation here} finally {session. close ();}

The configure method of configuration is configured using the application configuration file or the

Then, this configuration creates an isessionfactory instance through the buildsessionfactory method.

An isessionfactory instance opens an isession instance through opensession, uses this instance to complete database operations, and then closes it.

If you need transactions in your code, you only need to modify the code slightly.

Code example (changed the data in the database and added, deleted, and modified the data ):

// Configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // define the transaction itransaction Tx = NULL; // open isessionisession session = factory. opensession (); try {// start transaction Tx = session. begintransaction (); add operation TX here. commit ();} catch (hibernateexception ex) {If (TX! = NULL) Tx. rollback (); throw ex;} finally {// close isessionsession. Close ();}

I usually use transactions in methods that do not affect data (for example, query) and affect data (for example, add, delete, and modify.

 

3. Configuration File

The configure method of configuration needs to use the application configuration file or hibernate. cfg. XML file. Here I use hibernate. cfg. xml configuration file. In the next chapter, we will explore the application configuration file and other configuration methods.

This is a typical configuration file:

<? XML version = "1.0" encoding = "UTF-8"?>
<Hibernate-configuration xmlns = "urn: nhibernate-configuration-2.0">
<Session-factory name = "ddlly. mydoc. nhib.pdf. Quickstart">
<! -- Property -->
<Property name = "connection. provider"> nhib.pdf. Connection. driverconnectionprovider </property>
<Property name = "connection. driver_class"> nhib.pdf. Driver. sqlclientdriver </property>
<Property name = "connection. connection_string"> Server =.; database = user; uid = sa; Pwd = sa; </property>
<Property name = "show_ SQL"> false </property>
<Property name = "dialect"> nhib.pdf. dialect. mssql2000dialect </property>
<Property name = "use_outer_join"> true </property>
<Property name = "query. substitutions"> true 1, false 0, yes 'y', no 'n' </property>
<! -- Ing file -->
<Mapping Assembly = "ddlly. mydoc. nhib.pdf. Quickstart"/>
</Session-factory>
</Hibernate-configuration>

The connection. provider attribute sets the database connection provider (which generally does not need to be changed unless you decide to implement the provider yourself ).

Connection. driver_class sets the driver class of the database (the driver class of sqlserver is set here ).

Connection. connection_string is the connection string of the database.

Show_ SQL sets whether to display the SQL statements being executed on the console at runtime (this attribute is useful when debugging programs ).

Dialect is the Nhibernate dialect that enables nhibect to use the features of certain database platforms.

Use_outer_join will be introduced in later sections.

Query. Substitutions: replace some phrases in the Nhibernate query with SQL phrases (for example, phrases may be functions or characters ).

The ing node sets the ing file to be used. The current setting method is to use all the ing files in "ddlly. mydoc. nhib.pdf. Quickstart.

 

Iv. ing files

How does isession know which table to deal with and which field of the database, and how to associate the table with the object? It depends on the ing file.

Let's assume that we have a very simple example. We have a table that requires data operations (the Field and table meaning can be understood at first glance, so I won't bother with it ):

CREATE TABLE [dbo].[users] ([Id] [int] IDENTITY (1, 1) NOT NULL ,[UserName] [nvarchar] (64)  NOT NULL ,[Password] [varchar] (32)  NOT NULL ,[Email] [varchar] (64)  NULL )

We set its ing file and corresponding code file:

<?xml version="1.0" encoding="utf-8" ?> 
<class name="DDLLY.MyDoc.NHibernate.QuickStart.User, DDLLY.MyDoc.NHibernate.QuickStart" table="users">
<id name="Id" type="Int32">
<generator class="identity" />
</id>

<property name="UserName" type="String"/>
<property name="Password" type="String"/>
<property name="Email" type="String"/>
</class>
public class User{public User(){}private int m_Id;private string m_UserName;private string m_Password;private string m_Email;public int Id {get { return m_Id; }set { m_Id = value; }}public string UserName {get { return m_UserName; }set { m_UserName = value; }}public string Password {get { return m_Password; }set { m_Password = value; }}public string Email {get { return m_Email; }set { m_Email = value; }}}

<Class name = "ddlly. mydoc. nhib.pdf. quickstart. user, ddlly. mydoc. nhib.pdf. quickstart "table =" users "> indicates that the class file corresponding to the ing file is ddlly. mydoc. nhib.pdf. ddlly In the Quickstart assembly. mydoc. nhib.pdf. quickstart. user class. The comma (,) is followed by an assembly. The corresponding database table is users.

<ID name = "ID" type = "int32">
<Generator class = "Identity"/>
</ID>

Indicates that ID is the primary key field, and generator is the generator, which is generated using the built-in identification field in sqlserver.

Property defines other fields.

 

5. complete code

Now, we can start to operate on the data.

Let's take a look at the common methods that isession provides for us.

Load: Read object

Find: Use hql to find object

Save: Save object

Delete: deletes an object.

With these methods, we can add, delete, modify, and query databases. The following is the code I completed (using nunit for testing ).

Using system; using system. collections; using system. data; using system. data. sqlclient; using Nhibernate. CFG; using nunit. framework; namespace ddlly. mydoc. nhib.pdf. quickstart {// <summary> // user test class /// </Summary> [testfixture] public class userfixture {# region constant // connection string const string connectionstring = "Server = .; database = user; uid = sa; Pwd = sa; "; # endregion # region setup and teardown [setup] public void Setup () {// Add a user named lly with a password of 123456. Because this is the first record of the database, the database ID is 1 string setupsql = "insert into users ([username], [Password]) values ('lil', '000000') "; sqlexecutenonquery (setupsql);} [teardown] public void teardown () {// clear the users table, and clears the identity string teardownsql = "truncate table users"; sqlexecutenonquery (teardownsql );} # endregion # region private method // <summary> // execute an SQL statement // </Summary> /// <Param name = "SQL"> SQL statement </ param> P Rivate void sqlexecutenonquery (string SQL) {sqlconnection con = new sqlconnection (connectionstring); con. open (); sqlcommand cmd = new sqlcommand (); cmd. connection = con; cmd. commandtext = SQL; cmd. executenonquery (); con. close () ;}# endregion # region test method // <summary> /// test the read user /// </Summary> [test] public void testloaduser () {user = NULL; // configure configurationconfiguration CFG = new configuration (). configure (); // create an isessi Onfactoryisessionfactory factory = cfg. buildsessionfactory (); // open isessionisession session = factory. opensession (); Session = factory. opensession (); try {user = session. load (typeof (user), 1) as user;} finally {session. close ();} ************ * *************** // check assert. isnotnull (user, "No user with ID 1 found! "); Assert. areequal (" lly ", user. username," No user named lly found! ") ;}/// <Summary> /// test to find the user /// </Summary> [test] public void testfinduser () {ilist userlist = NULL; // configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // open isessionisession session = factory. opensession (); string hql = "from user as u where u. username = 'lil' "; Session = factory. opensession (); try {userlist = session. find (hql);} f Inally {session. close ();} ************ * *************** // check assert. areequal (1, userlist. count, "the number of users whose names are lly is not 1! ") ;}/// <Summary> /// test to add a user /// </Summary> [test] public void testadduser () {user newuser = new user (); // configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // define the transaction itransaction Tx = NULL; // open isessionisession session = factory. opensession (); try {// start transaction Tx = session. begintransaction (); newuser. username = "DDL"; newuser. pass WORD = "123456"; newuser. email = "DDLLY@tom.com"; // Save the new user session. save (newuser); Tx. commit ();} catch (hibernateexception ex) {If (TX! = NULL) Tx. rollback (); throw ex;} finally {// close the isessionsession. close ();} ************ * **************** ilist userlist = NULL; string hql = "from user as u where u. username = 'ddler' "; Session = factory. opensession (); try {userlist = session. find (hql);} finally {session. close ();} // check whether there is only one user named DDL assert. areequal (1, userlist. count, "the number of users whose names are DDL is not 1! ") ;}/// <Summary> /// test to delete a user /// </Summary> [test] public void testdeleteuser () {ilist userlist = NULL; user user = NULL; // configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // define the transaction itransaction Tx = NULL; // open isessionisession session = factory. opensession (); try {// start transaction Tx = session. begintransaction (); User = session. load (typeof (u Ser), 1) as user; Session. Delete (User); Tx. Commit ();} catch (hibernateexception ex) {If (TX! = NULL) Tx. rollback (); throw ex;} finally {session. close ();} ************ * *************** string hql = "from user as u where u. username = 'lil' "; Session = factory. opensession (); try {userlist = session. find (hql);} finally {session. close ();} // check assert. areequal (0, userlist. count, "the user whose name is lly is not deleted! ") ;}/// <Summary> /// test and update the user /// </Summary> [test] public void testupdateuser () {user = NULL; // configure configurationconfiguration CFG = new configuration (). configure (); // create isessionfactoryisessionfactory = cfg. buildsessionfactory (); // define the transaction itransaction Tx = NULL; // open isessionisession session = factory. opensession (); try {// start transaction Tx = session. begintransaction (); User = session. load (typeof (user), 1) as user; User. Password = "123"; Session. Update (User); Tx. Commit () ;}catch (hibernateexception ex) {If (TX! = NULL) Tx. rollback (); throw ex;} finally {session. close ();} ************ * **************** session = factory. opensession (); try {user = session. load (typeof (user), 1) as user;} finally {session. close ();} // check assert. isnotnull (user, "No user named lly found! "); Assert. areequal (" 123 ", user. password," No user named lly found! ") ;}# Endregion }}

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.