Chapter 4 AttributesNHibernate. Mapping. Attributes

Source: Internet
Author: User
Chapter 4 Use AttributesNHibernate. Mapping. Attributes

Directory

How to use it?
Prompt
Known issues and TODOs
Developer notice

What is NHibernate. Mapping. Attributes?

NHibernate. Mapping. Attributes is an additional software for NHibernate. It is Pierre Henri Kuat (akaKPixel) Contributed; the previous real-time player was John Morris.Nhib.pdf requires ing information to bind your domain object to the database. They are usually written (and saved in) in scattered hbm. xml files.

Use nhib.pdf. mapping. attributes, you can use. NET attribute (attributes) to modify your entity and be used to generate. hbm. attributes ). Therefore, you will no longer worry about these annoying files.

The contents in this library include.

  • Nhibtes. Mapping. Attributes: The only project you need (as an end user)

  • Test: A simple use case for using attributes (attributes) and HbmSerializer. It is TestFixture of NUnit.

  • Generator: The program used to generate attributes (attributes) and HbmWriter.

  • Refly: Thanks to Jonathan de Halleux for providing this library, which makes code generation so simple.

Important

This library uses files/src/NHibernate.Mapping.Attributes/nhibernate-mapping-2.0.xsd(It is embedded in the Assembly to check the legality of the generated XML Stream. this file may change every time a new version is released in nhib.pdf, so you should use it in different versions to regenerate it (open the Generator project, compile and run the Generator project ). however, in versions earlier than 0.8, it did not pass the test.

How to use it?

End user classYesNHibernate.Mapping.Attributes.HbmSerializer. This class serializes your domain model to the ing stream. You can serialize classes in the Assembly one by one.NHibernate.Mapping.Attributes.TestIt can be used as a reference.

Step 1: use attributes to modify your object. You can use[Class],[Subclass],[JoinedSubclass]Or[Component]. Then, modify the members (field/attribute properties); They can replace the attributes that need to be used in many mappings (attributes), for example:

    [NHibernate.Mapping.Attributes.Class]    public class Example    {        [NHibernate.Mapping.Attributes.Property]        public string Name;    }

After completing this step, useNHibernate.Mapping.Attributes.HbmSerializer(Here we use Default, which is an instance and used when you do not have to/do not want to create it yourself ).

System. IO. memoryStream stream = new System. IO. memoryStream (); // where the xml will be written nhib.pdf. mapping. attributes. hbmSerializer. default. validate = true; // Enable validation (optional) // Here, we serialize all decorated classes (but you can also do it class by class) nhib.pdf. mapping. attributes. hbmSerializer. default. serialize (stream, System. reflection. assembly. getExecutingAssembly (); stream. position = 0; // Rewind nhib.pdf. cfg. configuration cfg = new nhib.pdf. cfg. configuration (); cfg. configure (); cfg. addInputStream (stream); // Use the stream here stream. close (); // Now you can use this configuration to build your SessionFactory...
Note:

As you can see:

Nhibtes. Mapping. Attributes isNo(Real) invasive. setting attributes on your objects does not force you to use them in nhib.pdf and does not undermine any constraints in your architecture. attributes are pure information.

Prompt
  • UseHbmSerializer.ValidateTo enable/disable the legality check of the generated xml Stream (depending on nhib1_mapping schema); this is useful for quick search (they are written by StringBuilder)HbmSerializer.Error). If the error is expected by this database, the database will check whether it is a known problem and report it. Solving these problems can help you complete your solution.

  • Your class, field, and attribute properties (Members) can be private. Please make sure you have the permission to access private members Using Reflection (ReflectionPermissionFlag.MemberAccess).

  • The members of the ing Class are also located in the base class (until the mapped base class is found ). therefore, you can modify the member in the base class (without ing) and use it in its (ing) subclass.

  • For (System.Type), Use Name = "xxx" (as string) to set the type or set NameType = typeof (xxx); (Add "type" to "Name ")

  • By default ,.. NET attributes (attributes) do not maintain the order of attributes (attributes). Therefore, you must set the order by yourself. When you manage the order (use the first parameter of each attribute ). we strongly recommend that you set it when one of your members has more than one attribute.

  • As long as there is no ambiguity, you can define many irrelevant attributes (attributes) on the members ). A good example is the class-related attribute (attributes) on the identifier member (similar to the authenticator<discriminator>). But do not forget the management order (<discriminator>Must be in<id>). The order comes from the order of elements (elements) in the nhib1_mapping schema. In my opinion, I prefer to use negative numbers on attributes (if they are in the front !).

  • You can add[HibernateMapping]To specifyAttribute (attributes) (used when the class is serialized into a stream). You can also useHbmSerializer.Hbm*Properties (when[HibernateMapping]The modified type or assembly is used when it is serialized ).

  • Do not use a string as the authenticator value (DiscriminatorValue) (IN[Class]And[Subclass]), You can use it on any object you need. Example:

    [Subclass(DiscriminatorValueEnumFormat="d", DiscriminatorValueObject=DiscEnum.Val1)]

    Here, the object is an enumeration, you can set the format you need (the default value is "g"). Note that you must put it inFront! For other types, the object is simply used.ToString()Method.

  • If you useNullables.NullableXXXType members (in the library Nullables), the system automatically mapsNullables.NHibernate.NullableXXXType; You do not need[Property]Set inType="..."(Leave it blank). Thanks to Michael Third's idea.

  • Each stream produced by nhib.pdf. Mapping. Attributes has a date generated comment. You can use the methodWriteDateCommentEnable/disable it.

  • If you forget to provide a required xml attribute, the system will throw an exception when creating the ing.

  • Ing[Component]Is recommended and the simplest way is to use[ComponentProperty].
    First, place[Component]In the component class and map its fields/attributes. Be sure not[Component]Set the name. Then, add[ComponentProperty]But you cannot change the access (Access), Update (Update) Or insert (Insert).

    There is an example in nhib.pdf. Mapping. Attributes. Test (note:CompAddressClass and its use in other classes ).

    Note the last thing:ComponentPropertyAttributeYesfromDynamicComponentAttributeInherited, it is easy to write it immediately<component>After the element, it is in the XML stream.

  • Another ing[Component]The method is that it uses this method to make the library work: If a class contains a component ing, this component will be included by the class. NHibernate. Mapping. Attributes. TestJoinedBazAndStuffUse address (Address) Component example.

    Very simple. After adding

    [Component(Name = "MyComp")] private class SubComp : Comp {}

    One advantage of all classes is the ability to change the access (Access), Update (Update) Or insert (Insert). However, you must add the Child class of the componentEachClass (and it cannot be inherited ).

  • About custom.HbmSerializerUseHbmWriterSerialize attributes (attributes ). Its method is virtual; therefore, you can create a subclass and override any method (to change its default behavior ).

    Use property)HbmSerializer.HbmWriterTo change the implementer. (You can setHbmWriter).

Example with some prompts: (0, 1 and 2 are arranged in order)

    [NHibernate.Mapping.Attributes.Id(0, TypeType=typeof(int))] // Don't put it after [ManyToOne] !!!        [NHibernate.Mapping.Attributes.Generator(1, Class="uuid.hex")]    [NHibernate.Mapping.Attributes.ManyToOne(2, ClassType=typeof(Foo), OuterJoin=OuterJoinStrategy.True)]    private Foo Entity;

Generated:

    <id type="Int32">        <generator class="uuid.hex" />    </id>    <many-to-one name="Entity" class="Namespaces.Foo, SampleAssembly" outer-join="true" />

Known issues and TODOs

First, read the TODOs in the source code.

PositionProperty is added to all attributes (attributes) for sorting. But there are still problems:

When a parent element "p" has a child element "x", another child element "c" has a child element "x ". : D

    <p>        <c>            <x />        </c>        <x />    </p>

In this example, write:

    [Attributes.P(0)]        [Attributes.C(1)]            [Attributes.X(2)]        [Attributes.X(3)]    public MyType MyProperty;

X (3) will belong to C (1 )! (Same as X (2)

Below is<dynamic-component>And<nested-composite-element>.

Another bad message is that the XML elements added later cannot be contained. For example, there is no way<dynamic-component>Place the set. The reason isnhibernate-mapping-2.0.xsdThe file tells the program how elements are created, in what order they are created, and nhib.pdf. Mapping. Attributes uses them in this order.

In short, the solution should add an integer ParentNode attribute (property) to BaseAttribute so that you can create a real situation...

In fact, there are no other knowledge points and no planned modifications. This database will become a stable and complete version. However, if you find any problems or have effective improvement ideas, please contact us!

Another message, which is better than nhib.pdf. Mapping. Attributes. Test TestFixture.: D

Developer notice

Schema (nhibernate-mapping-2.0.xsd) Any change means:

  • Check whether any changes are required in Generator (such as updating KnowEnums/AllowMultipleValue/IsRoot/IsSystemType/IsSystemEnum/CanContainItself)

  • Update/src/NHibernate.Mapping.Attributes/nhibernate-mapping-2.0.xsd(Copy/paste) and run Generator again (even if you haven't modified it)

  • Run the test project and confirm that no known exception is thrown. modify/Add a class/attribute (property) (=> Update hbm) in this project to ensure that the damage caused by changes can be grasped. xml file and/orNHibernate.Mapping.Attributes-1.1.csprojProject Reference)

This implementation is based on nhib1_mapping schema. Many "Standard schema Features" may not be supported...

This version of nhib.pdf. Mapping. Attributes needs to be generated using the schema of the nhib.pdf library version.

The Design and Performance of this project are very small goals, and implementation and maintenance are much more important.

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.