Nhib1_cookbook study Note 5

Source: Internet
Author: User

Handle version and concurrency issues:

1. Modify the basic type of entity and add a version field.

protected virtualint Version { get; set; }

2. Add the version element to the product ing file.

<natural-id mutable="true">  <property name="Name"not-null="true" /></natural-id><version name="Version" /><property name="Description" /><property name="UnitPrice" not-null="true" />

 

3. The actorrole ing file also adds a version element:

<id name="Id">  <generator class="guid.comb"/></id><version name="Version" /><property name="Actor" not-null="true" /><property name="Role" not-null="true" />

4. Considering this situation, two users get data from the database at the same time. The first change is submitted. After a while, 2nd changes are submitted, and the first change is overwritten. There are two ways to handle this concurrency problem:

 

Optimistic Concurrency: When submitted by 2nd users, the version will be checked. If not, an exception will be thrown. Changes in version will automatically increase every time new data is updated.

See this SQL statement:

UPDATE ProductSET    Version = 2 /* @p0 */,       Name = 'Junk' /* @p1 */,       Description = 'Cool' /* @p2 */,       UnitPrice = 100 /* @p3 */WHERE  Id = '764de11e-1fd0-491e-8158-9db8015f9be5'/* @p4 */       AND Version = 1 /* @p5 */

Pessimistic concurrency: the lock mechanism. Once a user acquires data and obtains an exclusive lock, the transaction session. Lock method of NH is used to implement the lock.

 

Other optimistic concurrent processing:

<class name="Product" dynamic-update="true" optimistic-lock="dirty">

This method generates the following SQL statement and only checks the changed attributes: (Dynamic-update = "true" must be set for this method ")

UPDATE ProductSET    Name = 'Junk' /* @p0 */WHERE  Id = '741bd189-78b5-400c-97bd-9db80159ef79'/* @p1 */       AND Name = 'Stuff' /* @p2 */

The following configuration checks all fields to make sure they are not changed:

<class name="Product" dynamic-update="true" optimistic-lock="dirty">

The generated SQL statement is as follows:

UPDATE ProductSET    Name = 'Junk' /* @p0 */WHERE  Id = 'd3458d6e-fa28-4dcb-9130-9db8015cc5bb'/* @p1 */       AND Name = 'Stuff' /* @p2 */       AND Description = 'Cool' /* @p3 */       AND UnitPrice = 100 /* @p4 */

Code:

1. Add a new folder, copy the previous five classes to the folder, and then add a mapping folder to the folder. Note that you must add a producer. Because the version field is used for ing in our productmapping, the protect access permission will cause this attribute to not be found.

2. We can add the following code in productmapping to map it directly:

public class ProductMapping : ClassMap<Product> {    public ProductMapping() {        Id(p => p.Id).GeneratedBy.GuidComb();        DiscriminateSubClassesOnColumn("ProductType");        Version(p => p.Version);        NaturalId().Not.ReadOnly().Property(p => p.Name);        Map(p => p.Description);        Map(p => p.UnitPrice).Not.Nullable();    }}

3. Book ing:

public class BookMapping : SubclassMap<Book> {    public BookMapping() {        Map(p => p.Author);        Map(p => p.ISBN);    }}

4. Movie ing:

public class MovieMapping : SubclassMap<Movie> {        public MovieMapping() {            Map(m => m.Director);            HasMany(m => m.Actors).KeyColumn("MovieId").AsList(l => l.Column("ActorIndex"));        }}

5. actorrle ing:

public class ActorRoleMapping : ClassMap<ActorRole> {    public ActorRoleMapping() {        Id(ar => ar.Id)            .GeneratedBy.GuidComb();        Version(ar => ar.Version);        Map(ar => ar.Actor)            .Not.Nullable();        Map(ar => ar.Role)            .Not.Nullable();    }}

Fluent Nhibernate provides 2 ing methods: one is to manually write ing, and the other is automatic ing. above we all write ing manually, and each class corresponds to a ing Class.

All ing classes must inherit from classmap, and a subclass in the inheritance system must inherit from subclassmap, naturalid (). not. readonly (). property (P => P. name); this is the same effect as mutable = "true" in the configuration file. All attributes are expressed in map () format. One-to-multiple attributes are represented by hasiterator (), which can be followed
ASMAP (), asbag (), asset (), or aslist () correspond to several Collection types in the configuration file. aslist can use column to specify the index column.

Bidirectional one-to-multiple binding:

How to Create a bidirectional one-to-multiple relationship:
1. Add a class:

namespace ManualRelationships {    public class Order {        public virtual Guid Id { get; protected set; }        public Order() {            _items = new HashedSet<OrderItem>();        }        private Iesi.Collections.Generic.ISet<OrderItem> _items;        public virtual IEnumerable<OrderItem> Items {            get {                return _items;            }        }        public virtual bool AddItem(OrderItem newItem) {            if (newItem != null && _items.Add(newItem)) {                newItem.SetOrder(this);                return true;            }            return false;        }        public virtual bool RemoveItem(          OrderItem itemToRemove) {            if (itemToRemove != null &&              _items.Remove(itemToRemove)) {                itemToRemove.SetOrder(null);                return true;            }            return false;        }    }}

2. Add an order list class:

namespace ManualRelationships {    public class OrderItem {        public virtual Guid Id { get; protected set; }        public virtual Order Order { get; protected set; }        public virtual void SetOrder(Order newOrder) {            var prevOrder = Order;            if (newOrder == prevOrder)                return;            Order = newOrder;            if (prevOrder != null)                prevOrder.RemoveItem(this);            if (newOrder != null)                newOrder.AddItem(this);        }    }}

3. Order ing file:

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

4. Order item ing file:

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

In the preceding configuration file, order indicates order to control the relationship. Inverse = "true" indicates order to maintain the foreign key relationship. If you want to add an order with an orderitem in it, the generated SQL statement is as follows:

INSERT INTO "Order" (Id) VALUES (@p0)INSERT INTO OrderItem (Id) VALUES (@p1)UPDATE OrderItem SET OrderId = @p0 WHERE Id = @p1

If you specify inverse = "true" in the orderitem configuration file, the orderitem controls the foreign key relationship. The obtained statement is as follows:

INSERT INTO "Order" (Id) VALUES (@p0)INSERT INTO OrderItem (OrderId, Id) VALUES (@p0, @p1)

Sometimes uninitialized objects may be used in attribute settings. We recommend that you do not directly specify the foreign key relationship. Instead, manually add some methods:
Additem, removeitem, and setorder are manually specified. Pay attention to this two-way processing. The items in the order should be added, and the order in the items should also be added, so that the items will be associated.

In addition, because order is a keyword in the database, it should be enclosed in quotation marks.

 

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.