[Original] fluent nhib.pdf Tour 2-entity Mapping

Source: Internet
Author: User

Next, let's talk about ORM ing in Orm today. If you want to experience the strength of Nhibernate, you must first learn the configuration, including the configuration of sessionfactory and mapping. Today, like the previous article, we will use the traditional method and nhib.pdf to explain it. If you want to test it by yourself, you can first take a look at "fluent nhib.pdf journey 1" to prepare the database and sessionfactory.

Content of this section:
    • Simple Object ing
    • Ing object attributes using custom types

The entity mapping of Nhibernate is very good. Although it is not perfect, it is often used and basically supported, and the configuration is relatively simple. Now, let's start our experience journey.

1. Simple Object ing

We will start with a simple e-commerce platform in order to cooperate with future tutorials. For B2C e-commerce, we need products and orders. Because it is an example, it is as simple as possible. We first design two tables: Order and product.

First, we need to write the entity model. This model is required in both traditional and fluent methods.

 Public class  Product { Public Virtual int Productid { Get ; Set ;}Public Virtual string Name { Get ; Set ;} Public Virtual decimal Price { Get ; Set ;} Public Virtual  Datetime Createtime { Get ; Set ;}} Public class  Order { Public Virtual int Orderid {Get ; Set ;} Public Virtual decimal Price { Get ; Set ;} Public Virtual  Orderstate State { Get ; Set ;} Public Virtual  Datetime Createtime { Get ; Set ;}} Public Enum Orderstate {Created, paied, consignment, complete ,}

In a brief introduction, the Order has attributes such as order number, total price, order status, and creation time. The status is now int type. Then I will demonstrate how to use Enumeration type. The product has the product ID, product name, price, and creation time. Today's content does not involve associations, so we will not talk about order today.

Now, let's startCodeDemo stage.

Traditionally, XML files are used for ing. The configuration file is as follows:

 <  Hibernate-Mapping  Xmlns  = " URL: nhibernate-mapping-2.2 " Namespace  = " Entitymodel " Assembly  = " Entitymodel " > <  Class  Name  = " Product " Table  = " Product " > <  ID  Name  = " Productid " > <  Generator Class  = " Native " /> </  ID  > <  Property  Name  = " Name " > <  Column  Name  = " Name " Length  = " 50 " SQL-type  = " Varchar (50) " Not-Null  = " True " /> </  Property  > <  Property  Name  = " Price " > <  Column Name  = " Price " SQL-type  = " Real " Not-Null  = " True " /> </  Property  > <  Property  Name  = " Createtime "> <  Column  Name  = " Createtime " SQL-type  = " Datetime " Not-Null  = " True " /> </  Property  > </  Class  > </ Hibernate-Mapping  > 

The Order ing is generally similar to the product.

Fluent mode: You may think that we have used the configuration file for ing, which is quite simple. You can configure it as needed. But actually, I prefer the fluent ing mode, the ing code is as follows:

 
Public classProductmap:Classmap<Product> {PublicProductmap () {ID (M => M. productid); Map (M => M. Name); Map (M => M. Price). columnname ("Price"); Map (M => M. createtime );}}

We only need to inherit the fluent classmap <t> class, and then complete the ing method in the constructor method to complete the ing of the traditional method. The ing method is simple. I believe everyone can understand it. Why is it so convenient? This actually relies entirely on lambda expressions. Let's take a look at Lao Zhao's "Evolution of delegate writing in the. NET Framework", which makes it very clear. Let's take a look at ID and map

ID (expression <func <t, Object> expression, because ......, We only need a simple M => M. productid. You may say that the primary key type and the primary key has many features. Do you not need to configure it? The answer is yes, of course. Because the attribute name here is the same as the primary key name in the table, we didn't set it. If your database's primary key name is ID, here we only need ID (M => M. productid ). columnname ("ID"), you can see the price in the above ing, I used it, in fact, it does not matter, but just for demonstration. Of course there are many more, because with smart sensing, we only need. you can see a lot of methods at a glance, but pay attention to one thing ,. after columnname (), you cannot configure it any more. Therefore, you need to put other configurations before columname.

Map (expression <func <t, Object> Expression): similar to ID, it corresponds to the property in nhib.pdf. Here I am just a simple ing and there are many features, it will be used in future tutorials.

The comparison between the two can be understood only after they are used. For beginners like me, fluent is more suitable for me, because I can use it to learn nhib.pdf.

After the ing is completed, we will add the ing to the configuration in nhib.pdf.

Traditional methods:

 
<MappingAssembly="Mynhib.pdf"/>

Fluent:

 
Private StaticIsessionfactoryCreatesessionfactory (){ReturnFluently. Configure (). Database (Mssqlconfiguration. Mssql2005. connectionstring (S => S. Server ("."). Database ("Mynhib.pdf"). Trustedconnection (). mappings (M => M. fluentmappings. addfromassembly (Typeof(Fluentsessionfactory). Assembly). exportto ("C: \ path"). buildsessionfactory ();}

The method of FLUENT is better than the mappings method in the previous article. There are many mappings configuration methods. Here I use the simplest fluentmappings. addfromassembly, as long as the entity mapping is addedProgramSet. Of course there are more methods. If you want to know more, you can take a look at fluent nhib.pdf API document.

Here we will introduce mappingconfiguration. exportto (string path) method, which can automatically generate your entity ing HBM. XML file to the path you specified, we can generate HBM. XML file. Let's take a look at the Nhibernate ing method. This is a very good method. Sometimes, when I perform ing, I generate problems and check the problem at any time, so it is a very useful method, and you can directly use your ing file in the nhib.pdf project.

We have mapped the product. Let's test it. This time, we use the traditional method to insert data and the fluent method to obtain data. The test code is as follows:

[ Testmethod ] Public void Nhibernatefactory (){ VaR Factory = Tradsessionfactory . Getcurrentfactory (); Using (Isession Session = factory. opensession ()){ Product Product = New  Product (); Product. createtime = Datetime . Now; product. Name = "First product" ; Product. Price = 15; Session. Save (product );}}[ Testmethod ] Public void Fluentfactory (){ VaR Factory = Fluentsessionfactory . Getcurrentfactory ();Using ( VaR Session = factory. opensession ()){ Product Product = session. Load < Product > (1 ); Assert . Areequal ( "First product" , Product. Name );}}

If our ing is correct, the two unit tests should all pass. Next, let's take a look at the test results:

As we expected, the test passed, indicating that there was no error in our ing.

Ii. ing object attributes using custom types

Nhibernate supports ing attributes using custom types. However, since I am a beginner, I really don't know. Of course, I have found relevant materials on the Internet, let's talk about the fluent method. When I map custom attributes, that is, map (), I want to see what other methods of map, and the result shows customtypeis () and customtypeis <t> () two methods, one Using Reflection, one using generic, strong type, of course I will choose the latter. For the convenience of the next step, I will generate fluent mapping to my traditional mapping directory, add it to the project, and set it to embedded resources. Everything will be for future tutorials, in other words, in subsequent tutorials, I usually use FLUENT for ing, while the traditional method is used for learning.

In the order object, we can see that I used the orderstate Enumeration type for order status, and the database storage type is tinyint. For its ing, we only need:

 
Public classOrdermap:Classmap<Order> {PublicOrdermap () {ID (P => P. orderid); Map (P => P. Price); Map (P => P. State). customtypeis <Orderstate> (); Map (P => P. createtime );}}

Yes, it's that simple. You can understand it. You don't need to explain it. Even if my English is so bad, you can understand it, I believe that my friends in the blog community must understand it better than me. In the traditional method of ing, I have read the generated file, which is not very complex. In addition, I think the generated file is more standard than what I wrote. By the way.

 <  Hibernate-Mapping  Xmlns  = " URL: nhibernate-mapping-2.2 " Default-Access  = "" > <  Class  Name  = " Entitymodel. Order, entitymodel, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "Table  = " 'Order' " Xmlns  = " URL: nhibernate-mapping-2.2 " > <  ID  Name  = " Orderid " Type  = " Int32 " Column  = "Orderid " > <  Generator  Class  = " Identity " /> </  ID  > <  Property  Name  = " Price " Type  = " Decimal "> <  Column  Name  = " Price " /> </  Property  > <  Property  Name  = " State " Type  = " Entitymodel. orderstate, entitymodel, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "> <  Column  Name  = " State " /> </  Property  > <  Property  Name  = " Createtime " Type  = " Datetime " > < Column  Name  = " Createtime " /> </  Property  > </  Class  > </  Hibernate-Mapping  > 

Next, we will test the addition of order in fluent mode. The code for obtaining this order in traditional mode is as follows:

[ Testmethod ] Public void Nhibernatefactory (){ VaR Factory = Tradsessionfactory . Getcurrentfactory (); Using ( VaR Session = factory. opensession ()){ Order Order = session. Load < Order > (1 ); Assert . Areequal ( Orderstate . Created, order. State ); Assert . Areequal (200, order. Price );}}[ Testmethod ] Public void Fluentfactory (){VaR Factory = Fluentsessionfactory . Getcurrentfactory (); Using ( VaR Session = factory. opensession ()){ Order Order = New  Order () {Price = 200, state = Orderstate . Created, createtime = Datetime . Now}; Session. Save (Order );}}

Old rule, Cuihua, test result:

It's good. Everything is normal. Today's code is here.

Summary

Today we introduced how to map simple entities, but most of the time this is an ideal data design, there are more complex, unpredictable data design, this time we can do fluent? I don't know the answer. At least when I solve the problem, I think the fluent method is more convenient than the traditional method. At least during the test, I don't need to map the file, the configuration file is copied to the test project again. Nhibernate is a powerful ORM framework. I know him too much and it takes some time to master it.

A few days ago, the opening of "fluent Nhibernate trip 1" was not a good response. Maybe there are very few people who use Nhibernate. Maybe I did not write well enough, maybe .... However, this does not affect my desire to complete this series, because I have encountered too many problems that are difficult to solve, and I have learned a lot in solving them. I hope I can share all these issues with you, as for the good and the bad, let's evaluate it later.

PS: I can finally access the Internet. It's been a long time, haha.

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.