Nhibernate 4.0 Tutorials Getting Started

Source: Internet
Author: User
Tags modifiers

Nhibernate 4.0 Tutorials

Directory

1. Download NHibernate 4.04. 1

2. Getting Started tutorial ... 2

3. Test Project Details ... 3

4. Summary ... 7

Attached: Associated knowledge points ... 7

Knowledge points 1:c# Static constructors ... 7

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

Objective:

Why is there such a framework? This is involved in Java and C # 's resentment, Java is an open-source object-oriented language representative, around Java has countless open source framework, which ORM framework (don't ask me what is ORM Framework) the most dazzling representative is hibernate;c# It is also the object-oriented language that Microsoft is following in Java, the two similarities are too large (I read my own study of Java, C # there is no special learning, directly to use). NET developers also developed an ORM framework for the. NET platform, known as NHibernate, with Hibernate.

Development environment:

Windows 7

Visual Studio 2013

Nhibernate 4.04

Microsoft SQL Server 2012

    1. Download NHibernate 4.04

Direct Download website address http://nhibernate.info/(self-download speed is 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.

NHibernate is a mature, open-source, relational database mapping (ORM) for the. NET Framework.

Or use the NuGet Manager program that came with VS2013 to install directly (NuGet,. NET under an open source package management tool): Install-package Nhibernate (very fast)

    1. Getting Started tutorials

Create a new project Nhone and test program, and add a test project for the project, the project schema is as follows:

Key points: Among the configuration files for NHibernate (Hibernate.cfg.xml and classmapping files, for generated operations, always copy and embedded resources must be selected.) (otherwise there will be bugs when compiling and debugging, such as mapping without model class, etc.).

    1. Test Project detailed

3.1 Initializing the C # solution Nhone (console application and corresponding test project)

Add a nhibernate reference to each project, and the test project also needs to be installed (directly with the NuGet command)

3.2 Writing NHibernate configuration files

Add Hibernate.cfg.xml file (Build Action Embedded Resource and always copy) in Nhone root directory, schema selection in document properties hibernate-configuration-2.2 & hibernate-mapping-2.2 two files, so write hibernate.cfg.xml will have automatic prompt function (these two files in our solution Nhone Packages/nhibernate directory)

Hibernate.cfg.xml specific contents are as follows:

<?xml version= "1.0" encoding= "Utf-8"?>

<session-factory>

<property name= "Connection.provider" >NHibernate.Connection.DriverConnectionProvider</property>

<property name= "Connection.driver_class" >NHibernate.Driver.SqlClientDriver</property>

<property name= "connection.connection_string" >data source=localhost;user=sa;password=12345;initial Catalog= Test</property>

<property name= "dialect" >NHibernate.Dialect.MsSql2012Dialect</property>

<property name= "Show_sql" >true</property>

<property name= "Hbm2ddl.auto" >update</property>

<!--Mapping files Embedded Resource Table table name cannot be user-->

<mapping assembly= "Nhone"/>

</session-factory>

<mapping assembly= "Nhone"/> Here is the name of the project, and then it will search for all the suffixes below the project. hbm.xml files, can also be manually added, more trouble, have the opportunity to explain in detail.

3.3 Writing model Class "User"

All properties are decorated with virtual (lazy loading is useful), and the corresponding get set method is added

In Msserver, user is a keyword, so you cannot have a user table, you can use the other instead

In practice, each model class may need to provide an override 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 Writing the model's mapping file

Under the mapping directory, create a new file User.hbm.xml file (embedded resource, the schema of the add File is 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, and if omitted, the complete namespaces and class names will be populated in the following class name attribute.

Note that the name of table cannot be written as user, otherwise error, because user is the key word of the database

The contents are as follows:

<?xml version= "1.0" encoding= "Utf-8"?>

<class name= "User" table= "Client" >

<id name= "id" >

<column name= "user_id" sql-type= "char (+)" 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>

3.5 Write the NHibernate helper class, initialize the NHibernate environment, get the session

Under the Util namespace, add the Yangnhibernate class with the following details:

Namespace Nhone.util

{

public class Yangnhibernate

{

private static readonly isessionfactory sessionfactory;

private static string hibernatehbmxmlfilename = "Hibernate.cfg.xml";

private static ISession session

Static Yangnhibernate ()

{

Sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();

}

public static Isessionfactory Getsessionfactory ()

{

return sessionfactory;

}

public static ISession getsession ()

{

return Sessionfactory.opensession ();

}

public static void Closesessionfactory ()

{

}

}

}

3.6 Writing Test Code

Testing the mechanism for saving user-to-database, using transactions in a test class

[TestMethod]

public void Testsaveuser ()

{

User user = CreateUser ();

ISession session = Yangnhibernate.getsession ();

ITransaction tx = Session. BeginTransaction ();

Session. Save (user);

Tx.commit ();

Session. Close ();

}

Debug Program:

    1. Summarize

NHibernate is a C # programmer, referring to the Java ORM Framework hibernate implementation of an open source project, in C # project development is very convenient and efficient, so that the program ape from the complex SQL statements freed up, the project is very useful for modularity.

The source code address of the test project:

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

Reference Documentation:

    1. NHibernate official website http://nhibernate.info/
    2. MSDN for C#:HTTPS://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/K9X6W0HC (v=vs.120). aspx

Attached: Associated knowledge points

Knowledge points 1:c# Static constructors

C # Knowledge of static constructors, automatic invocation of initialization of static member properties, especially readonly decorated static properties, similar to static blocks of code in Java.

Refer to MSDN for explanations:

A Static constructor is used to initialize any static data, or to perform a particular action that needs to be performed O NCE only. It is called automatically before the first instance was created or any static members are referenced.

(HTTPS://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/K9X6W0HC (v=vs.120). aspx)

Because the static constructor is. NET is called automatically, so you do not need to use modifier modifiers to change the code block.

About the characteristics of C # static constructors, as follows:

A Static constructor does not take access modifiers or has parameters.

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

A Static constructor cannot be called directly.

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

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

Static constructors is also useful when creating wrapper classes for unmanaged code, when the constructor can call the Lo Adlibrary method.

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

Knowledge point 2: About Visual Studio file generation operations

The Visual Studio build operation has several options:

Non (None): That is, when the project is generated without any action, in the generated directory does not have this file, generally used in the project description file.

Content: The file is copied directly into the output directory, usually used for static files such as HTML.

Compile (Compile): Compile code files, common code files need to be compiled

Embedded Resource (Embedded Resource): Embeds the file as a DLL or executable file in the home directory, typically for resource files such as nhibernate configuration files, and so on.

Nhibernate 4.0 Tutorials Getting Started

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.