Chapter 4-isessionfactory Configuration

Source: Internet
Author: User
Tags log4net
Recording
Programmable Configuration
Obtain isessionfactory
Users provide their own ADO. net connection
Nhib.pdf provides ADO. net connection
Optional Properties
SQL dialect (SQL dialects)
Outer Join fetching)
Custom CacheProvider
Query Language replacement
Logging

Because nhib.pdf is designed to work in many different environments, it has many configuration parameters. Fortunately, most of them already have default values. Nhib.pdf. Test. dll contains an example configuration file.app.configIt demonstrates some variable parameters.

Programmable Configuration

NHibernate.Cfg.ConfigurationAn instance represents a set of mappings between all. Net classes in the application and the SQL database.ConfigurationUsed to construct an (immutable)ISessionFactory. These mappings are compiled from some XML ing files.

You can getConfigurationInstance. The following example is used to initialize two xml configuration files (in the same directory as the EXE file:

Configuration cfg = new Configuration()    .AddXmlFile("Item.hbm.xml")    .AddXmlFile("Bid.hbm.xml");

Another (sometimes better) method is to enable nhib.pdf to use it on its own.GetManifestResourceStream()To load the ing File

Configuration cfg = new Configuration()    .AddClass( typeof(NHibernate.Auction.Item) )    .AddClass( typeof(NHibernate.Auction.Bid) );

Nhibernate will findNHibernate.Auction.Item.hbm.xmlAndNHibernate.Auction.Bid.hbm.xml. This method cancels all hard encoding of file names.

Another (possibly the best) method is to allow nhib.pdf to read all the configuration files in an assembly:

Configuration cfg = new Configuration()    .AddAssembly( "NHibernate.Auction" );

Nhib.pdf will traverse the Assembly to find anyhbm.xml. This method cancels all hard encoding of the file name and ensures that the configuration file in the Assembly is loaded.

Make sure that the HBM. xml file is used as an embedded Resource (Embedded Resources.

ConfigurationYou can also specify some optional configuration items.

Hashtable props = new Hashtable();...Configuration cfg = new Configuration()    .AddClass( typeof(NHibernate.Auction.Item) )    .AddClass( typeof(NHibernate.Auction.Bid) );cfg.Properties = props;

ConfigurationIs an object used only during the configuration period. It becomes invalid when it is created from the first sessionfactory.

Obtain isessionfactory

When all mappings areConfigurationAfter parsing, the applicationISessionInstance, you must first obtain its factory. This factory should be shared by all threads of the application:

ISessionFactory sessions = cfg.BuildSessionFactory();

Of course, nhib.pdf does not prohibit your program from instantiating multipleISessionFactory. This is useful when you use more than one database.

Users provide their own ADO. net connection

ISessionFactoryYou can use a user-provided ADO. net connection to openISession. This design allows applications to manage their own ADO. net connections:

IDbConnection conn = myapp.GetOpenConnection();ISession session = sessions.OpenSession(conn);// do some data access work

The application must be careful not to open two parallelISession!

Nhib.pdf provides ADO. net connection

Another way isISessionFactoryOpen the connection for you. Sessionfactory must know the parameters of the ADO. net connection in advance. There are several different methods to set parameters:

  1. By providingIDictionaryInstanceConfiguration.Properties.

  2. InnhibernateOfSystem.Configuration.NameValueSectionHandlerType.

  3. Inhibernate.cfg.xmlContains<property>Element.

If you use this method, openISessionIt is very simple:

ISession session = sessions.OpenSession(); // open a new Session// do some data access work, an ADO connection will be used on demand

All the attributes and constraints of Nhibernate areNHibernate.Cfg.EnvironmentClass. We will discuss the most important settings of the ADO. net connection Configuration:

If you set the following attributes, Nhibernate uses ADO. NET data provider to get the connection:

Table 2.1. nhib1_ado. NET attributes

Attribute name Purpose
hibernate.connection.provider_class CustomizationIConnectionProviderType.

For example:full.classname.of.ConnectionProvider(If the provider is created in nhib.pdf), orfull.classname.of.ConnectionProvider, assembly(If you use the implementation of a custom iconnectionprovider interface, it does not belong to Nhibernate ).

hibernate.connection.driver_class CustomizationIDriverType.

full.classname.of.Driver(If the driver class is created in nhib.pdf), orfull.classname.of.Driver, assembly(If you use the implementation of a custom idriver interface, it does not belong to nhib.pdf ).

hibernate.connection.connection_string Used to obtain the connection string.
hibernate.connection.isolation Set the transaction isolation level. Please checkSystem.Data.IsolationLevelTo get the specific meaning of the value and view the database documentation to ensure that the level is supported.

For example: Chaos, ReadCommitted, ReadUncommitted, RepeatableRead, Serializable, Unspecified

Below isweb.configExample of specifying the connection property in the file:

<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections>  <section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System,     Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections>  <nhibernate>  <add    key="hibernate.connection.provider"             value="NHibernate.Connection.DriverConnectionProvider"   />  <add    key="hibernate.connection.driver_class"             value="NHibernate.Driver.SqlClientDriver"   />  <add    key="hibernate.connection.connection_string"    value="Server=127.0.0.1;Initial Catalog=thedatabase;Integrated Security=SSPI"   />  <add    key="hibernate.connection.isolation"   value="ReadCommitted"  />  <add    key="hibernate.dialect"                         value="NHibernate.Dialect.MsSql2000Dialect"   />   </nhibernate>  <!-- log4net (required by NHibernate) and other app specific config follows --></configuration> 
Optional Properties

The following are some other configurations that can change the Nhibernate action at runtime. All of these are optional and have reasonable default values.

Table 2.2. Configure attributes of nhib.pdf

Attribute name Purpose
hibernate.dialect Class Name of the nhibect dialect (dialect)-enables nhibect to use features of certain database platforms

For example: full.classname.of.Dialect(If the dialect is created in nhib.pdf), orfull.classname.of.Dialect, assembly (If a custom dialect is used, it does not belong to nhib.pdf ).

hibernate.default_schema In the generated SQL statement, the full qualified name of scheml/tablespace.

For example: SCHEMA_NAME

hibernate.prepare_sql

Prepare SQL statements?

For example: true|false

hibernate.session_factory_name SessionFactoryThis name will be automatically bound after it is created.

For example: some.name

hibernate.use_outer_join Allow external connection capturing.

For example:true|false

hibernate.cache.provider_class Specify a customCacheProviderClass Name of the cache provider

For example: full.classname.of.CacheProvider(If icacheprovider is created in Nhibernate), orfull.classname.of.CacheProvider, assembly(If you use a custom icacheprovider, it does not belong to nhibprovider ).

hibernate.query.substitutions Replace some phrases in the Nhibernate query with SQL phrases (for example, phrases may be functions or characters ).

For example: hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

SQL dialect (SQL dialects)

You can always sethibernate.dialectDialect, which isNHibernate.Dialect.Dialect. If you do not need to usenativeOrsequenceAutomatically generate an algorithm for the primary key of or use pessimistic lockingISession.Lock()OrIQuery.SetLockMode()), You do not need to specify the dialect. However, if you specify a dialect, Hibernate uses special default values for some attributes listed above, saving you from manually specifying them.

Table 2.3.Nhib1_ SQL Dialect(hibernate.dialect)

RDBMS Dialect
DB2 NHibernate.Dialect.DB2Dialect
PostgreSQL NHibernate.Dialect.PostgreSQLDialect
MySQL NHibernate.Dialect.MySQLDialect
Oracle (Any Version) NHibernate.Dialect.OracleDialect
Oracle 9/10g NHibernate.Dialect.Oracle9Dialect
Sybase NHibernate.Dialect.SybaseDialect
Microsoft SQL Server 2000 NHibernate.Dialect.MsSql2000Dialect
Microsoft SQL Server 7 NHibernate.Dialect.MsSql7Dialect
Firebird NHibernate.Dialect.FirebirdDialect
Outer Join fetching)

If your database supports ANSI or Oracle-style external connections, external connection crawling may improve performance, because the number of interactions with the database can be limited (the cost is that the database itself does more work ). External Connection capturing allows youSELECTStatement to obtain an object graph composed of multiple to one or one-to-one connections.

By default, when a leaf object is crawled, an object with a proxy or a reference to itself is generated, it is terminated.

For a specific Association, you can setouter-joinAttribute can control whether to enable the capture function.

Sethibernate.use_outer_joinIsfalseDisable Global External Connection capturing. SettrueAll one-to-one (one-to-one) and many-to-one (one-to-one) connections are enabled for external join capturing. By default, it is set to auto, that is, automatic external connection. However, one-to-multiple associations and collections will never use external connections to capture, unless each specific association is explicitly stated. This row can be reloaded through nhib.pdf query at runtime.

Custom CacheProvider

ImplementationNHibernate.Cache.ICacheProviderInterface, you can integrate a second-level cache. You can usehibernate.cache.provider_classSelect a custom implementation.

Query Language replacement

You can usehibernate.query.substitutionsDefine a new Nhibernate query phrase. For example:

hibernate.query.substitutions true=1, false=0

In the generated SQL statement, the phrasetrueAndfalseReplace it with an integer.

hibernate.query.substitutions toLowercase=LOWER

This allows you to rename the SQLLOWERFunction.

Logging

Through Apache log4net, nhib.pdf records many events.

You canhttp://logging.apache.org/log4net/To download log4net. To use log4net, you must configure the log4net node in APP. config or web. config.src/NHibernate.TestThere is a configuration example in the project.

We strongly recommend that you familiarize yourself with the log information of Nhibernate's. Much of the work of Nhibernate's will be kept as detailed as possible, and it has not become difficult to read. This is the most basic facility for solving the problem.

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.