NHibernate3 anatomy: Mapping's Conform Combat (1): overview

Source: Internet
Author: User
Tags create database schema

Orum thought emerges

We are so familiar with ORM (Object Relational Mapping), but we can imagine the idea of Orum (Object Relational un-mapping) from an angle.

We only define domain in the program, and we want to have a tool that can help us to "self-actively" implement mapping. We don't need to manually code mapping for domain as traditional ORM thought.

Orum is more like the meaning of Oram (object-relational auto-mapping) or Orim (object-relational intelligent-mapping) for the user.

Is there such an implementation? The answer is quite certain.

Conform overview

Conform, a nhibernate contributor Fabio Maulo, is a tool for configuring ORM, which interfaces in accordance with the ORM concept, based on the GNU Lesser General Public License protocol.

The source of design thought is Orum (Object relational un-mapping). It helps us to implement mapping "on our own initiative" in accordance with domain definitions.

Now only the "Self-initiative" Mapping to NHibernate is realized. If you are interested, you can join the EF to implement your own active mapping function.

So how does conform "own initiative"?

NHibernate the process of mapping. is to deserialize the XML file into the Hbmmapping class. Then the Hbmmapping class bind to mappings, finally bind sessionfactory. The conform is the use of domain definitions to implement their own initiative to generate Hbmmapping class. Completely avoids the writing of XML files and deserialization. In this case, conform is playing the role of Orawm "object to relational adapter without mappings".

You can get conform to http://code.google.com/p/codeconform/.

Conform Preliminary interview

This is the first article in this series, we use a simple example to implement it, and then slowly introduce its details.

First we write down the NHibernate base code and common code, and this step of code is often used in future articles. I will not post it separately.

//code Snippets Copyright http://lyj.cnblogs.com/Public Static ClassNhconfig{Private Const stringConnectionString =@ "Data source=.\sqlexpress;initial catalog=nhtest;integrated security=true; Pooling=false ";Public StaticConfigurationConfigurenhibernate () {varConfigure =NewConfiguration(); Configure. Sessionfactoryname ("Demo"); Configure. Proxy (p = p.proxyfactoryfactory<proxyfactoryfactory> ()); Configure. Databaseintegration (db = {db). dialect<Mssql2008dialect> (); Db. driver<Sqlclientdriver> (); Db.                                              ConnectionString = ConnectionString; Db. Logsqlinconsole =true;//For displaying output SQL});returnConfigure }Public static StringSerialize (hbmmappingHbmelement) {varsetting =Newxmlwritersettings{Indent =true};varSerializer =NewXmlSerializer(typeof(hbmmapping));using(varMemstream =NewMemoryStream(2048))using(varXmlWriter =XmlWriter. Create (Memstream, setting)) {serializer.            Serialize (XmlWriter, hbmelement);            Memstream.flush (); memstream.position = 0;varSR =NewStreamReader(Memstream);returnSr.        ReadToEnd (); }    }}

The Configurenhibernate () method is used to configure the Nhibernate,serialize method for output.

Let's start the Conform tour:

1. Define a domain

Start the journey. We always start from the simplest, in the future to learn conform how to "self-initiative" for our complex domain structure generated mapping.

//Code Snippets Copyright http://lyj.cnblogs.com/Domain{    getset; }    getset; }}
2.ConfORM Configuration

This step is important, is the core of conform, instantiate a Objectrelationalmapper object, assemble the domain object, instantiate the Mapper object, invoke the Compilemappingfor () of the Mapper object method to generate hbmmapping on its own initiative.

//Code Snippets Copyright http://lyj.cnblogs.com/public static HbmMapping GetMapping(){    var orm = new ObjectRelationalMapper();    orm.TablePerClass<Domain>();    var mapper = new Mapper(orm);    return mapper.CompileMappingFor(new[] { typeof(Domain) });}
3.ConfORM Tour

The key part of this step is to call the Adddeserializedmapping () method of the Configuration object to add the hbmmapping and configuration metadata.

//code Snippets Copyright http://lyj.cnblogs.com/Public static voidJustforconform () {//Configuration NHibernatevarconf =Nhconfig. Configurenhibernate ();//Add hbmmapping to the configurationConf. Adddeserializedmapping (GetMapping (),"Domain");//Configure meta-dataSchemametadataupdater. Quotetableandcolumns (conf);//CREATE DATABASE schemaNewSchemaexport(conf). Create (false,true);//Establish sessionfactoryvarFactory = Conf. Buildsessionfactory ();//Open session to make persistent datausing(vars = Factory. Opensession ()) {using(vartx = S.begintransaction ()) {varDomain =NewDomain{Name ="my test."};            S.save (domain);        Tx.commit (); }    }//Open session to delete datausing(vars = Factory. Opensession ()) {using(vartx = S.begintransaction ()) {S.createquery ("Delete from Domain").            Executeupdate ();        Tx.commit (); }    }//Delete database schemaNewSchemaexport(conf). Drop (false,true);}
4. Output XML

All right. Done 3 steps above. Our test: NHibernate to create the database schema, persist data, delete data, and finally delete the database schema.

Now everyone has a question. Conform self-generated hbmmapping is what ah? What exactly does the serialized Hbmmapping object output? In order to meet the needs of our people, we write a section of code to let conform print out XML, compare our previous handwritten *.hbm.xml file to see if it matches:

//Code Snippets Copyright http://lyj.cnblogs.com/ public static void  showxmlmapping () {var  document = nhconfig .    Serialize (GetMapping ()); file .    WriteAllText ( "MyMapping.hbm.xml" , document); console . Write (document);}  

Then. We open the output folder of the MyMapping.hbm.xml file to see the contents:

//code Snippets Copyright http://lyj.cnblogs.com/<?XMLversion="1.0"encoding="Utf-8"?><hibernate-mappingXmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="Http://www.w3.org/2001/XMLSchema"namespace="Yjinglee.conform"Assembly="Yjinglee.conform"xmlns="urn:nhibernate-mapping-2.2"> <classname="Domain"> <IDname="Id"type="Int32"> <Generatorclass="Hilo"/> </ID> < Propertyname="Name"/> </class></hibernate-mapping>

Well, it's the same handwriting. Conform can be aware of members of the domain class. The ID primary key uses the Hilo build policy, name is property. Gee, is it just the way it is generated? The answer is certainly not. Conform offers a very multi-modal and customized approach, which is described in the future.

Only use the second step of the lines of code to complete their own active mapping function, is not very cool, after reading this article. Are you very eager to follow me to learn the next conform, and then try to focus on their own old program, throw away hibernate.cfg.xml and *.hbm.xml files AH.

Conclusion

This article first took everyone into the conform. The details are then introduced slowly, we have any questions and thinking can reply.

Attach source code Download: YJingLee.TryConfOrm.zip (VS2010 project)

NHibernate3 anatomy: Mapping's Conform Combat (1): overview

Related Article

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.