[C #] nhib.pdf handling multiple sets of books

Source: Internet
Author: User

I have long heard of ORM for a long time, but it was the first two weeks to learn it. I finally decided to take a good look at nhib.pdf (ibatisnet, however, due to limited time, it will be put on hold for the time being.) The first reason is that hibernate is famous. The second reason is that it is open-source and has the opportunity to look at its source code!
After searching for the Internet for a long time, I did not find a few documents, and I could not just chew on the hibernate documents. Soon I found a problem: Does nhib.pdf seem unable to operate several databases at the same time? Assume that a distributed system has n clients and an application. Program Server, multiple database servers, the client can connect to different database servers through the Application Server according to its own configuration (should be Tingtang Description of the so-called multiple sets of books), how should nhib.pdf handle this situation? If you know a little about the configuration of Nhibernate, you probably know that it is through configuration. buildsessionfactory obtains the isessionfactory interface. In this method, we can only use the connection string to specify a default database, in the article "using nhib.pdf in window form", we mentioned that you can connect to other databases by adding a configuration file. However, if you want to use the second database, this means that the second expensive buildsessionfactory call is required. If we allow users to create and delete databases, the configuration file is not flexible enough. How can we achieve our goal?
Check the Nhibernate Doc and accidentally find that opensession has an overload method. You can provideIdbconnection It seems that God has an eye, intuition tells me that it is it !!! After the experiment, you only need to specify this parameter to easily change the connected database dynamically! Let's talk about it. Code ......
The first is the sessionfactory code. Here, sessionfactory is implemented as a Singleton, mainly because it is extremely time-consuming and labor-consuming to create sessionfactory, which can avoid repeated creation.

Using System;
Using System. reflection;
Using System. diagnostics;
Using System. Data;

Using Nhib.pdf;
Using Nhib.pdf. cfg;

Namespace Myproject. Services
{
Public   Class Sessionfactory
{
Private   Static Configuration _ Configuration =   Null ;
Private   Static Isessionfactory _ Factory =   Null ;

Static Sessionfactory ()
{
_ Configuration =   New Configuration ();

_ Configuration. setproperty ( " Hibernate. Dialect " , " Nhib.pdf. dialect. mssql2000dialect " );
_ Configuration. setproperty ( " Hibernate. Connection. Provider " ,
" Nhib.pdf. Connection. driverconnectionprovider " );
_ Configuration. setproperty ( " Hibernate. Connection. driver_class " ,
" Nhib.pdf. Driver. sqlclientdriver " );
_ Configuration. setproperty ( " Hibernate. Connection. connection_string " ,
@" Server = localhost; initial catalog = Master; Integrated Security = sspi " );

_ Configuration. addassembly (assembly. Load ( " Myproject. Beans " ));
_ Factory = _ Configuration. buildsessionfactory ();
}

Public   Static Isession opensession ()
{
Debug. Assert (_ Factory! = Null,"Isessionfactory is null");
Return_ Factory. opensession ();
}

Public   Static Isession opensession (idbconnection connection)
{
Debug. Assert (_ Factory ! =   Null , " Isessionfactory is null " );
Debug. Assert (connection ! =   Null , " Idbconnection is null " );
Return _ Factory. opensession (connection );
}

Public   Static   Void Initialize ()
{
//Do nothing, just trigger the static. ctor
}
}
}

You can find that my connection is actuallyMasterDatabase, hey, that's the secret. When you call buildsessionfactory, it doesn't matter which database you specify. You can specify that no database is faulty. Of course, the consequence of doing so is that youRequiredSpecify a connection during opensession. Otherwise, you will be at your own risk!
Well, the above is all the key points. The next step is how to use them. Here is an example to illustrate how to use it:

Public   Static   Void Testadduser (User newuser)
{
String Connstring =   @" Server = localhost; initial catalog = gcs2; Integrated Security = sspi " ;
Using (Sqlconnection Conn =   New Sqlconnection (connstring ))
{
Conn. open ();
Isession session = Sessionfactory. opensession (Conn As Idbconnection );
Itransaction transaction = Session. begintransaction ();
Try
{
Session. Save (newuser );
Transaction. Commit ();
}
Catch (Exception ex)
{
Transaction. rollback ();
ThrowEx;
}
Finally
{
Session. Close ();
}
}
}

The call code is as follows:

Private   Void Btnadd_click ( Object Sender, eventargs E)
{
User newuser =   New User ();
Newuser. Name =   " <New user> " ;
Newuser. Password =   " <None> " ;
Newuser. createdate = Datetime. now;
Newuser. lastlogin = Datetime. now;
Userfactory. testadduser (newuser );
}

If there is no problem, the final user will be saved to the gcs2 database, instead of the master database! In fact, by changing the connection string in the testadduser member function (which can be passed by the client), where do you want to connect? Haha!

Of course, you can also see that,Forcible connection is at the cost of code portability.I have forcibly specified sqlconnection as the actual connection here. Of course, this problem is well solved. A simple factory is more than enough. Well, enjoy it!

Note: This is myFirst timePublishArticleAnd I am not very familiar with it. If you have any omissions or errors, please correct me!

"The End 』

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.