NHibernate 快速入门 已翻译 100%

徐继开 投递于 2013/07/11 23:56 (共 20 段, 翻译完成于 07-13)
阅读 17612
收藏 66
5
加载中

This tutorial will take you through your first NHibernate project, illustrating the basic steps required for configuration and mapping.

To keep things focused, we will begin with a very simple example to get you started.  And to keep the code to a minimum, we'll be putting aside unit tests and interface code, and focus exclusively on just enough code to persist our data and illustrate some basic CRUD (Change, Read, Update, Delete) techniques.    

The tools used in this and other examples include:

Microsoft SQL Server 2005 Express Edition - This will house our persistent data.  This tutorial will also work with SQL Server 2008.  For the purposes of our example, we will assume you have a local instance of SQL Server and are familiar with working with SQL Management Studio. 

NHibernate version 2.1.2 - You can download the latest version of NHibernate at the following link:  http://sourceforge.net/projects/nhibernate/files/NHibernate/

Microsoft Visual Studio 2008 - our development environment.

已有 1 人翻译此段
我来翻译


Creating our Project File

Since we're not going to be focusing on the user interface in this example, we will start by creating a new Console Application project:

For the purposes of this tutorial, we will be calling our application 'HelloNHibernate'.  I would recommend sticking to that naming convention and also following along with the various examples and names used, since in many cases these names may be used in other parts of the tutorial.

已有 1 人翻译此段
我来翻译

Adding a reference to NHibernate

Our next step is to add a series of references needed for NHibernate to function effectively.  When you downloaded and extracted your NHibernate installation, several directories were created, including 'Required_bins' and 'Required_for_LazyLoading.

First, you will need to include all of the DLLs in Required Bins - these represent the core components used by NHibernate.

Next, we need to include all of the DLLs in one of the subfolders of Required_for_LazyLoading.  The choice of which set of DLLs you use for Lazy Loading is ultimately up to you, although for the purposes of this and other tutorials we will be using the Castle dynamic proxy.

 

已有 1 人翻译此段
我来翻译

Configuring NHibernate

With our references set up, we will now need to create and update our App.config (if this were a website, we would be modifying Web.config).  For our project, we are going to make a few assumptions:

  • We will be working with a local instance of SQL Server 2005 and have created our database.

  • We have a trusted connection to our database

  • We will be using the Castle proxy factory

  • We will be outputting our TSQL to the console (I strongly recommend this as you learn NHibernate, since it lets you see what it is doing under the hood).

Here is an example App.config containing just the pieces we will need for our tutorial.

<?xmlversion="1.0"encoding="utf-8" ?>

<configuration>

    <configSections>
        <sectionname="hibernate-configuration"requirePermission="false"type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
    </configSections>

    <hibernate-configurationxmlns="urn:nhibernate-configuration-2.2">
        <reflection-optimizeruse="false" />
        <session-factory>
            <propertyname="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
            <propertyname="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
            <propertyname="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
            <propertyname="connection.connection_string">Data Source=(local); Initial Catalog=quickstart; Trusted_Connection=true;</property>
            <propertyname='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
            <propertyname="show_sql">true</property>
        </session-factory>
    </hibernate-configuration>
</configuration>

You will see in our configuration that we are setting up NHibernate to use SQL Server and the SQL 2005 dialect for it's dynamic SQL.  You will also see our connection string (you can modify this as needed), our reference to the Castle Proxy Factory, and a flag (show_sql) telling NHibernate to output all TSQL statements to the console.

已有 1 人翻译此段
我来翻译

Creating our Model

NHibernate allows you to work directly with Plain Old CLR Objects (POCOs) instead of having to directly interact with the database via stored procedures.  One advantage of using POCOs is that we are not tied to a specific persistence layer.  For example, some ORM solutions require special attributes, or are based on your model objects inheriting from a specific base class. 

In the case of NHibernate, no special decoration is required to allow our objects to interact with our persistence layer.  The only concession we need to make for NHibernate is that all properties we wish to persist must be virtual, and if lazy loading is enabled, all public methods in our class must be virtual even if they are not included in our mapping file.

As a general rule of thumb, it's best to make all of your properties virtual, this way your bases are covered whether you use lazy loading or not.

已有 1 人翻译此段
我来翻译

Additionally, we can have properties and methods in our POCO that are not persisted, and can easily have multiple POCOs that map to the same table within our database.  For example, we may have one POCO that provides the complete detail screen of a product, including images and a comprehensive description, and another lightweight version that just includes the name and quantity that would be used to generate a product list.

For our tutorial, we will be creating an extremely simple object.  In the following tutorials, we will build upon this to cover more complex topics like parent/child relationships, advanced search techniques, etc. 

Create a new class in your project named 'Product' with the properties below.  Note that NHibernate is case sensitive, so our property names will need to exactly match our NHibernate mapping that we will be creating later.

namespace HelloNHibernate
{
    public classProduct
    {
        public virtual int? ProductId { get; set; }
        public virtual string ProductName { get; set; }
    }
}

Note that we've made the ProductId a nullable field.  This will allow us to create instances of this object without an ID, which in turn will tell NHibernate that this is a new object and not one that happens to have an ID of '0'.

已有 1 人翻译此段
我来翻译

Creating our NHibernate Mapping File

Nhibernate uses XML mapping files to map between our POCO and our database objects.  While in many cases these may be a one to one relationship, this is not compulsory.  You can easily change field names, and create different maps to create alternate presentation views for your database object.

For example, we could have a complex 'Product' object that included a large blob of narrative text, and a collection of associated orders along with complex inventory data.  While this map would be excellent for a detailed product view where we are editing a single product, it would be way too heavy to use as a member of a strongly types list used in a dropdown of products.  In the latter case, we could create a much simpler map to a presentation view that only has the product ID and product name.

For our tutorial, we will be working with a very simple map that directly relates to the POCO we created above.  To create a map, add a new XML file to your project as shown below.  When creating the xml file, it should end with .hbm.xml - this convention tells NHibernate that this is a mapping file.  We will name ours 'Product.hbm.xml'

 

已有 1 人翻译此段
我来翻译
Your XML mapping file should include the following information.  We will cover each of these tags below:
<?xmlversion="1.0"encoding="utf-8" ?>
<hibernate-mappingxmlns="urn:nhibernate-mapping-2.2"
                           assembly="HelloNHibernate"
                           namespace="HelloNHibernate">

    <class name="Product" table="Products">
        <id name="ProductId">
            <generatorclass="identity"/>
        </id>
        <property name="ProductName"length="50" />
    </class>
</hibernate-mapping>

  • Within the hibernate-maping tag, we're referencing both the assembly and namespace that the classes (POCOs) below reside in.  This is handy when your mapping files end up in a separate namespace or assembly than your model.

  • The class element represents our mapping to a single POCO.  The name represents the name of a class within the assembly and namespace from above, while the table attribute tells NHibernate which table or view in our database to map to

  • The id element tells NHibernate which database field and corresponding object property to use as a unique key.  In this case, we are using the ProductId field.

  • The generator element tells NHibernate how to create unique IDs for new entities.  Since we will be using the Identity attribute in SQL Server, we will specifiy the generator class as 'identity'.

  • The property tag is the tag you will see the most.  This simply maps a POCO property to the corresponding field in our table or view.  I've included the length attribute in our example since we will want to be able to generate a schema from this map, and the default of 255 characters is much larger than we will need for a product name.

已有 1 人翻译此段
我来翻译
Once your mapping file is created, you will need to make sure that you have it set as an embedded resource, otherwise NHibernate will be unable to read your XML file and mapping will not take place.  To do this, click on your new XML file in solution explorer, select properties, and change the Build Action for the XML file.

 

At this point, your solution should look like the solution shown below:

 

已有 1 人翻译此段
我来翻译
Connecting to our database using NHibernate

At this point, we have completed our configuration and setup, and we are ready to begin interacting with our database using NHibernate. 

Throughout these examples, I would recommend following along and observing how your objects change, and also how data persists to the database.  This will help you better understand how NHibernate works, and help reinforce the examples below as you observe your persistent data changing.

Now, for the code!  It's very important to note that in this first example, we're focusing only on the minimal code needed to work with persistent data via NHibernate , and not focusing on testability and other best practices.  As we move into more complex examples, we will spend some time building a more robust architecture that will serve as a better starting point for your live applications.

Within NHibernate, our root object will be an object implementing the ISessionFactory interface.  a SessionFactory is a fairly expensive object, and you should only need one for your application.

已有 1 人翻译此段
我来翻译
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
加载中

评论(25)

T
Troy_Zhang
可以学习
无聊的人啊
无聊的人啊

引用来自“北落”的评论

引用来自“都市网达”的评论

引用来自“北落”的评论

引用来自“秦时明月”的评论

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html

@红薯 这有打广告的 请速度来把Moon.Orm收了

Moon.Orm的自动生成很蛋痛

@秦时明月 速度来解答疑惑

自动生成什么?不爽的地方?
北落
北落

引用来自“都市网达”的评论

引用来自“北落”的评论

引用来自“秦时明月”的评论

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html

@红薯 这有打广告的 请速度来把Moon.Orm收了

Moon.Orm的自动生成很蛋痛

@秦时明月 速度来解答疑惑
Null--Null
Null--Null

引用来自“北落”的评论

引用来自“秦时明月”的评论

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html

@红薯 这有打广告的 请速度来把Moon.Orm收了

Moon.Orm的自动生成很蛋痛
无聊的人啊
无聊的人啊

引用来自“北落”的评论

引用来自“秦时明月”的评论

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html

@红薯 这有打广告的 请速度来把Moon.Orm收了

moon.orm已经收了
北落
北落

引用来自“秦时明月”的评论

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html

@红薯 这有打广告的 请速度来把Moon.Orm收了
徐继开
徐继开

引用来自“都市网达”的评论

把源码打包,提供下载,Could not compile the mapping document: ***.hbm.xml

http://sourceforge.net/projects/nhibernate/files/NHibernate/
无聊的人啊
无聊的人啊

引用来自“在会议中指出”的评论

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

的确 - -

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html
无聊的人啊
无聊的人啊

引用来自“北落”的评论

NHibernate2.2的时候用过,之后就没有使用的机会了。.Net下毕竟还是微软自己的东西好用

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html
无聊的人啊
无聊的人啊

引用来自“赵远明”的评论

记得用nh是几年前的事了

或许大家看见这么多配置文件都累了,
看看Moon.Orm,有多么强大.
http://www.cnblogs.com/humble/archive/2013/05/01/3052826.html
返回顶部
顶部
返回顶部
顶部