Nhib.pdf 4.0 getting started, nhibernate4.0

Source: Internet
Author: User

Nhib.pdf 4.0 getting started, nhibernate4.0

Nhib.pdf 4.0 tutorial

Directory

1. Download nhib.pdf 4.04. 1

2. Getting Started tutorial... 2

3. test project details... 3

4. Summary... 7

Appendix: related knowledge points... 7

Knowledge Point 1: C # static constructor... 7

Knowledge Point 2: About Visual Studio file generation operations... 8

 

 

Preface:

Why is there this framework? This involves the grievances of Java and C #. Java is a representative of open-source object-oriented languages, and there are countless open-source frameworks around Java, among them, the most dazzling representative of the orm framework (do not ask me what is an ORM framework) is Hibernate; C # is also an object-oriented language that Microsoft is following in Java, the similarity between the two is too large (I read the Java I learned, and I didn't have to study it later in C #, so I used it directly ),. NET developers have also developed. the ORM framework under the. NET platform, that is, nhib.pdf.

 

Development Environment:

Windows 7

Visual Studio 2013

Nhibbench 4.04

Microsoft SQL Server 2012

Directly download the official website address http://nhibernate.info/(own download speed really good slow)

NHibernate is a mature, open source object-relational mapper for the. NET framework. It's actively developed, fully featured and used in thousands of successful projects.

The official website introduced that nhib is a mature and open-source relational database ing (ORM) for. NET frameworks ).

Or use the NuGet management program that comes with VS2013 to directly Install (NuGet, an open-source Package management tool under. NET): Install-Package nhib.pdf (very fast)

 

 

Create a new project NHOne and test program, and add a test project for the project. The project architecture is as follows:

 

 

NOTE: For the configuration files (hibernate. cfg. xml and ClassMapping files) of Nhibernate, you must always copy and embed the generated operations. (Otherwise, bugs may occur during compilation and debugging, such as Model ing without Model Class ).

3.1 initialize C # solution NHOne (console application and corresponding test project)

Add a reference to nhibet for each project, and the test project also needs to be installed using the NuGet command)

3.2 compile the nhib.pdf configuration file

Add hibernate under the root directory of NHOne. cfg. xml file (generating embedded resources and always copying). In the document attributes, choose hibernate-configuration-2.2 & hibernate-mapping-2.2 For the architecture. In this way, compile hibernate. cfg. xml will have the automatic prompt function (these two files are in the packages/nhib.pdf directory of our solution NHOne)

 

 

The specific content of hibernate. cfg. xml is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>

<Hibernate-configuration xmlns = "urn: nhibernate-configuration-2.2">

<Session-factory>

<Property name = "connection. provider"> nhib.pdf. Connection. DriverConnectionProvider </property>

<Property name = "connection. driver_class"> nhib.pdf. Driver. SqlClientDriver </property>

<Property name = "connection. connection_string"> Data Source = localhost; user = sa; password = 12345; Initial Catalog = test </property>

<Property name = "dialect"> nhib.pdf. Dialect. MsSql2012Dialect </property>

<Property name = "show_ SQL"> true </property>

<Property name = "hbm2ddl. auto"> update </property>

<! -- Mapping files embedded resource table name cannot be user -->

<Mapping assembly = "NHOne"/>

</Session-factory>

 

</Hibernate-configuration>

 

<Mapping assembly = "NHOne"/> the project name is written here, and then all the suffixes under the project are searched. hbm. you can manually add xml files, which is troublesome and has the opportunity to explain in detail.

3.3 compile Model Class "User"

All attributes are modified using virtual (delayed loading is useful). Add the corresponding get set method.

In MSServer, user is a keyword, So there cannot be tables with users. You can use other words instead.

In practical applications, each model class may require rewriting of the Equals () HashCode () ToString () method.

Namespace NHOne. Model

{

Public class User

{

Private string id;

Private string username;

Private string password;

Private char gender; // "F" & "M"

Private int age;

Private string phone;

 

Public User ()

{

 

}

 

Public User (string username, string password, char gender, int age, string phone)

{

This. username = username;

This. password = password;

This. gender = gender;

This. age = age;

This. phone = phone;

}

 

Public User (string id, string username, string password, char gender, int age, string phone)

{

This. id = id;

This. username = username;

This. password = password;

This. gender = gender;

This. age = age;

This. phone = phone;

}

Public virtual string Id {get; set ;}

Public virtual string Username {get; set ;}

Public virtual string Password {get; set ;}

Public virtual char Gender {get; set ;}

Public virtual int Age {get; set ;}

Public virtual string Phone {get; set ;}

Public override bool Equals (object obj)

{

If (this = obj)

{

Return true;

}

User user = obj as User;

If (user = null)

{

Return false;

}

Else

{

Return this. Username. Equals (user. Username );

}

}

 

Public override int GetHashCode ()

{

Return Username. GetHashCode ();

}

 

Public override string ToString ()

{

Return "id:" + Id + "; Username:" + Username + "; Password:" + Password + "; Gender:" + Gender + "; Age: "+ Age +"; Phone: "+ Phone;

}

}

}

3.4 compile the Mapping file of the Model.

Create a new file User under the Mapping directory. hbm. xml file (embedded resource, adding file schema as hibernate-mapping-2.2.xml), the red part assembly is the name of the project, namespace is the namespace of the Model class in the project, if omitted, you must enter the complete namespace and class name in the class name attribute.

Note that the table name cannot be written as user. Otherwise, an error is reported because user is the keyword of the database.

The content is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>

<Hibernate-mapping xmlns = "urn: nhibernate-mapping-2.2" assemblies = "NHOne" namespace = "NHOne. Model" default-lazy = "true">

<Class name = "User" table = "client">

<Id name = "Id">

<Column name = "user_id" SQL-type = "char (32)" not-null = "true"/>

<Generator class = "uuid. hex"/>

</Id>

<Property name = "Username" column = "username" not-null = "true"/>

<Property name = "Password" column = "password" not-null = "true"/>

<Property name = "Gender" column = "gender"/>

<Property name = "Age" column = "age"/>

<Property name = "Phone" column = "phone"/>

</Class>

</Hibernate-mapping>

 

3.5 compile the NHibernate help class, initialize the NHibernate environment, and obtain the Session

Add the yangnhibibclass In the Util namespace. The specific content is as follows:

Namespace NHOne. Util

{

Public class yangnhib.pdf

{

Private static readonly ISessionFactory sessionFactory;

Private static string HibernateHbmXmlFileName = "hibernate. cfg. xml ";

// Private static ISession session

Static yangnhib.pdf ()

{

SessionFactory = new Configuration (). Configure (). BuildSessionFactory ();

}

Public static ISessionFactory getSessionFactory ()

{

Return sessionFactory;

}

Public static ISession getSession ()

{

Return sessionFactory. OpenSession ();

}

Public static void closeSessionFactory ()

{

}

}

}

 

3.6 write test code

Test in the test class to save the User to the database and use the transaction mechanism.

[TestMethod]

Public void TestSaveUser ()

{

User user = createUser ();

ISession session = yangnhib.pdf. getSession ();

ITransaction tx = session. BeginTransaction ();

Session. Save (user );

Tx. Commit ();

Session. Close ();

}

 

Debugging program:

 

 

 

Nhib.pdf is a C # programmer. It is very convenient and efficient in project development in C # by referring to an open-source project implemented by Java's ORM framework Hibernate, it frees programmers from complicated SQL statements and is very useful for project modularization.

Source Code address of the test project:

Https://github.com/hbhzsysutengfei/NHibernateOne.git

Reference:

Appendix: associated knowledge points

Knowledge Point 1: C # static Constructor

C # about static constructor, automatically call and initialize static member attributes, Especially static attributes modified by readonly, which is similar to static code blocks in Java.

Refer to the explanations provided by MSDN:

A static constructor is used to initialize any static data, or to perform a participant action that needs to be synchronized med once only. it is called automatically before the first instance is created or any static members are referenced.

(Https://msdn.microsoft.com/zh-cn/library/k9x6w0hc (v = vs.120). aspx)

Because the static constructor is automatically called by. NET, you do not need to use modifiers to modify the code block.

The features of the C # static constructor are as follows:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

 

Knowledge Point 2: Visual Studio file generation operations

Visual Studio has the following options:

Non (none): no operation is performed when the project is generated. This file is not in the generated directory and is generally used in the project description file.

Content: directly copies the file to the output directory, which is generally used for static files such as html.

Compile: Compile a code file.

Embedded Resource: this file is Embedded into the main directory as a DLL or executable file. It is usually used for Resource files, such as the configuration file of nhib.pdf.

 

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.