Nhib.pdf 2.0 References

Source: Internet
Author: User

1. The first nhib.pdf Application

 

 

1.1. Start the NHibernate journey

This tutorial demonstrates how to build an example of nhib1_2.0.0 in the Microsoft development environment. The following tools are used:

  1. Internet Information Service (IIS) Manager-Web servers supported by ASP. NET.

  2. SQL Server 2005-database Server. in this example, the desktop version (EXPRESS) is used and can be downloaded from Microsoft for free. nhib.pdf also supports other databases. Instead, you only need to change the database dialect and database driver in the configuration file.

  3. Visual Studio. NET 2005-development environment.

First, we create a Web project namedQuickStart. The project automatically createsHttp: // localhost/QuickStartVirtual directory.
Open a project and addNhib.pdf. dllReference. Visual Studio automatically copies the dependent files of the library you reference to your output directory. if you are using another database, add the corresponding data to access the Assembly to your project.

Now we start to configure database connection information for nhib.pdf. Before that, open the automatically generatedWeb. configAdd a configuration element as follows:

Nhib.pdf. Dialect. MsSql2005Dialect nhib.pdf. Connection. DriverConnectionProviderWeb. config <ConfigSections>The configuration file defines a configuration section and declares how the data in this configuration section is parsed.
<Hibernate-configuration>The configuration contains the configuration information of NHibernate, telling NHibernate that we use Microsoft SQL Server 2005 database and connect to the database through the specified connection string. dialect is a mandatory setting. Each database has different interpretations of the SQL standard.

Nhib.pdf uses dialect to eliminate the differences in interpretation of SQL standards between these open source or commercial databases.

ISessionFactoryIn nhib.pdf, a single data storage concept (corresponding to a database in SQLServer) can be used to create multiple XML configuration files and create multipleConfigurationAndISessionFactoryObject.

<Hibernate-configuration>The last element in the configuration section declaresQuickStartThe name of the application Assembly that contains the persistence class and the corresponding ing file.
The ing file contains metadata information mapped from the POCO class to one or more database tables.

The ing file will be mentioned later.

First, write a POCO class, and then write a database ing file for this class.

 

1.2. The first persistence class

Nhibts use a simple. Net object (Plain Old CLR Objects, which is POCOs, also known as Plain Ordinary CLR Objects)

This programming model is used for persistence. The POCO class accesses its internal member variables through the set and get attributes, and hides the internal implementation details (if necessary, nhib can also directly access its internal member variables ).

{Id = {name = {sex = {weight =}Object Cat. cs

 

Nhib.pdf does not impose any restrictions on the type used by the attribute.

All. NET types and original types (suchString,CharAndDateTime) Can be mapped, including. Net set (System. Collections.

You can map them to values, Value Sets, or be associated with other entity classes.

IdIt is a special attribute that represents the database identifier (primary key) of this class. It is strongly recommended for entity classes like Cat.
Nhib can also use internal identifiers, but we will lose some flexibility in the program architecture.

Persistence classes do not need to implement any special interfaces or inherit from a special persistence root class.
NHibernate does not need to be processed during the compilation period, such as the IL operation. It uses the. Net reflection mechanism and runtime class enhancement independently (through Castle. DynamicProxy2 library ).
Therefore, we can map POJO classes to database tables without relying on nhib.pdf.

To make the class enhancement function take effect as mentioned above, all public attributes of the NHibernate persistence class must be declaredVirtual.


 

 

1.3. Map cat

Cat. hbm. xmlThe ing file contains the metadata required for Object/relationship ing (O/R Mapping.
Metadata includes persistence class declarations and ing of attributes to the database (pointing to the foreign key association between fields and other entities ).

Note that Cat. hbm. xml must be set as an embedded resource in Visual Stuido ).

Cat. hbm. xml

 

Each persistence class should have an identifier attribute (in fact, this class only represents an object, rather than an independent value type class, which is mapped to a component in an object ).
This attribute is used to differentiate persistent objects: IfCatA. Id. Equals (catB. Id)If the result is true, the two cats are the same.
This concept is calledDatabase ID.

NHibernate comes with several different identifier generators for different scenarios (including database sequence generators, hi/lo high/low bit identification modes, and program-defined identifiers ).
Here we use the UUID generator (only recommended during testing, if you use the database's own Integer type key value is better), and specifyCatTableCatIdThe field (as the primary key of the table) stores the generated id value.

  CatOther attributes of are mapped to fields in the same table.
PairNameAttribute, we explicitly declare the ing to a database field.
This is especially useful if the database schema is automatically generated by the ing Statement (as an SQL DDL command.
All other attributes are mapped using the default value of nhib.pdf, which you will do in most cases.

In the databaseCatThe table looks like this:

 

You can create this table manually in your database. If you need to use the SchemaExport tool to automate this step, see section 17. toolbox guide.
This tool can create complete SQL DDL statements, including table definitions, Custom field type constraints, unique constraints, and indexes.


If SQL Server is used, make sure that ASP. Net users have the permission to access the database.


 

 

1.4. Be happy with Cat

Now we can start to useISession. It isPersistence Manager, We useISessionTo access the databaseCat.

First, we needISessionFactoryTo obtainISession(The unit of work of nhib.pdf ).

 ISessionFactory sessionFactory =  Configuration().Configure().BuildSessionFactory();

ISessionFactoryRepresents a database and uses an XML configuration file (Web. configOrHibernate. cfg. xml).
Nhibure loads the Configuration file by calling Configuration (). Configure () and initializes it into a Configuration instance.
CreateISessionFactory.

In the createISessionFactoryPreviously (it is immutable), you can access Configuration to set other attributes (or even modify the ing metadata ).

Where should we createISessionFactoryIn our program, how can we access it?

ISessionFactoryIt is usually only initialized once. For example, it is initialized in the Application_Start event. This means that you should not hold it as an instance variable on the ASP. NET page, but put it elsewhere.
Further, we need to useSingleton ModeIn order to make it easier to accessISessionFactory.

The following method solves two problems at the same time:ISessionFactoryInitial Configuration and convenient use.

The following implementsNHibernateHelperHelp class:

CurrentSessionKey = sessionFactory = HttpContext context = ISession currentSession = context. items [CurrentSessionKey] (currentSession = context. items [CurrentSessionKey] = HttpContext context = ISession currentSession = context. items [CurrentSessionKey] (currentSession = (sessionFactory! =}Help class NHibernateHelper. cs

 

This class does not need to be consideredISessionFactory, Should be set to static type, andISessionIn the http request.

ISessionFactoryIs a secure thread, which can be accessed and obtained by multiple threads concurrently.ISessionS.
SingleISessionIt is not a secure thread object. It only represents an operation with the database.
  ISessionPassISessionFactoryObtain and close after all work is completed.

ISession session = ITransaction tx = Cat princess = princess. Name = princess. Sex = princess. Weight = NHibernateHelper. CloseSession ();Get ISession and close it after completion

 

 

InISessionIn, each database operation is performed in a transaction, so that different operations (or even read-only operations) can be isolated ).
We useITransactionAPI to get out of the underlying transaction policy (in this example, it is an ADO. NET transaction.
Note that this example does not contain any exception handling.

  
Note:
You can callNHibernateHelper. GetCurrentSession ();Each time you get the Session of the same current request.
Whether in your Application_EndRequest code, Application_EndRequest, or before the HTTP result is returned, you must ensure that this Session is closed after your database access is completed.
The advantage of this is that lazy initialization can be easily used ):ISessionIt is still opened when rendering the view layer, so you can load the required objects when traversing the current object graph.

Nhib.pdf has different methods for retrieving objects from the database. The most flexible way is to use HQL, a language that is easy to learn and powerful extension of SQL object-oriented

(ITransaction tx = IQuery query = session. CreateQuery (query. SetCharacter (, (Cat cat Console. Out. WriteLine (+}Use HQL to query data

 

Hibernate also provides an object-orientedConditional QueryAPI.

Of course, nhib.pdf is used in all interactions with databases.IDbCommandAnd parameter binding.

You can also use the direct SQL query feature of nhib.pdf, orISessionObtain an original ADO. NET connection.

 

 

 

 

1.5. Summary

In this short tutorial, we have a taste of nhib.pdf.

Note that the example does not contain any ASP. NET code.

You must compile your own ASP. NET Page and insert the proper NHibernate code.

 

Remember that as a database access layer, nhib.pdf is closely related to your program.

Generally, all other layers depend on the persistence mechanism. Are you sure you understand the meaning of this design?

 

 

Qspace: http://778078163.qzone.qq.com
Blog: http://www.cnblogs.com/LonelyShadow

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.