Nhibernate 3.0 cookbook學(xué)習(xí)筆記 集合
Nhibernate支持四種集合:
1 Bags
Bags中的數(shù)據(jù)允許重復(fù),并且順序在Bag中是不重要的。比如一個(gè)ActorRole的Bag集合,可能包含actor role 1, actor role 2, actor role 3, actor role 1,
actor role 4, and actor role 1,它們中允許有重復(fù)項(xiàng)出現(xiàn)。下面是一個(gè)典型的Bag映射:
<bag name="Actors"> <key column="MovieId"/> <one-to-many class="ActorRole"/> </bag>
在相應(yīng)的類中,Bag的實(shí)現(xiàn)可以為IList、ICollection甚至 IEnumerable.
因?yàn)锽ag中的數(shù)據(jù)是可重復(fù)的,所以我們不能通過一條簡單的SQL語句如:delete from Actors where ActorRoleId='1'來確定刪除某一條數(shù)據(jù),如果執(zhí)行這條語句會(huì)把三個(gè)actor role 1的實(shí)體都刪除。
為了解決這個(gè)問題,Nhibernate提供了idBag.在idBag中,每一個(gè)實(shí)體都被分配了一個(gè)POID來唯一確定實(shí)體。
<idBag name="Actors"> <collection-id column="ActorRoleBagId" type="Int64"> <generator class="hilo" /> </collection-id> <key column="MovieId"/> <one-to-many class="ActorRole"/> </idBag>
這樣Nhibernate就可以像執(zhí)行這條語句:delete from Actors where ActorRoleBagId='2'一樣來刪除唯一的實(shí)體。
2 Lists
List中的數(shù)據(jù)也是可重復(fù)的,但與Bag不一樣,數(shù)據(jù)的所處位置是有意義的。一個(gè)List可能是index 0為actor role 1 , index 1為actor role 2, index 2為actor role 3, index 3為actor role 1,index 4為actor role 4,index 5為actor role 1.一個(gè)典型的List映射如下:
<list name="Actors"> <key column="MovieId" /> <list-index column="ActorRoleIndex" /> <one-to-many class="ActorRole"/> </list>
在相應(yīng)的類中,List的實(shí)現(xiàn)應(yīng)為IList。
3 Sets
Set中的數(shù)據(jù)是不允許重復(fù)的,數(shù)據(jù)出現(xiàn)的位置也無關(guān)緊要。在一個(gè)Set中,可能有actor role 1, actor role 3, actor role 2, 和 actor role 4.如果你嘗試向Set中插入actor role 1的實(shí)體,這個(gè)操作將為失敗。一個(gè)典型的Set映射如下:
<set name="Actors"> <key column="MovieId" /> <one-to-many class="ActorRole"/> </set>
在相應(yīng)的類中,Set的實(shí)現(xiàn)應(yīng)為來自Iesi.Collections.dll的ISet。
4 Map
Map就像一個(gè)字典,每一個(gè)集合中的實(shí)體都擁有一個(gè)key和一個(gè)value,并且key必須是唯一的。一個(gè)典型的映射如下:
<map name="Actors" > <key column="MovieId" /> <map-key column="Role" type="string" /> <element column="Actor" type="string"/> </map>
在相應(yīng)的類中,Map的實(shí)現(xiàn)應(yīng)為IDictionary<string, string>。
當(dāng)然,允許映射的數(shù)據(jù)類型有很多,不單單是string。一個(gè)Map的key或value的數(shù)據(jù)類型甚至可以是一個(gè)實(shí)體。
<map name="SomeProperty"> <key column="Id" /> <index-many-to-many class="KeyEntity"/> <many-to-many class="ValueEntity" /> </map>

浙公網(wǎng)安備 33010602011771號(hào)