public class CompositeUser { int _uid; UserName _name; public int Uid { get { return _uid; } set { _uid = value; } } public UserName Name { get { return _name; } set { _name = value; } } }
UserName.cs public class UserName { private string _firstName; private string _lastName; CompositeUser _user; public string FirstName { get { return _firstName; } set { _firstName=value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public CompositeUser User { get { return _user; } set { _user = value; } } }
映射文件:CompositeUser.hbm.xml <? xml version="1.0" encoding="utf-8" ?> < hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2" > < class name ="NhibernateSample1.CompositeUser,NhibernateSample1" table ="CompositeUser" lazy ="false" > < id name ="Uid" column ="Uid" unsaved-value ="0" > < generator class ="native" /> </ id > < component name ="Name" class ="NhibernateSample1.UserName,NhibernateSample1" > < parent name ="User" ></ parent > < property name ="FirstName" column ="FirstName" ></ property > < property name ="LastName" column ="LastName" ></ property > </ component > </ class > </ hibernate-mapping >
注意parent是指向容器对象的引用 加载一个CompositeUser对象,结果如图 4. 集合组合依赖 Composite.cs public class CompositeUser { int _uid; UserName _name; ISet _userNames = new HashedSet(); DateTime _birthDay = DateTime.Now; public int Uid { get { return _uid; } set { _uid = value; } } public ISet UserNames { get { return _userNames; } set { _userNames = value; } } public DateTime BirthDay { get { return _birthDay; } set { _birthDay = value; } } }
UserName.cs public class UserName { private string _firstName; private string _lastName; CompositeUser _user; public string FirstName { get { return _firstName; } set { _firstName=value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public CompositeUser User { get { return _user; } set { _user = value; } } }
映射文件CompositeUser.hbm.xml <? xml version="1.0" encoding="utf-8" ?> < hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2" > < class name ="NhibernateSample1.CompositeUser,NhibernateSample1" table ="CompositeUser" lazy ="false" > < id name ="Uid" column ="Uid" unsaved-value ="0" > < generator class ="native" /> </ id > < set name ="UserNames" table ="UserNames" lazy ="true" > < key column ="Uid" /> < composite-element class ="NhibernateSample1.UserName,NhibernateSample1" > < property name ="FirstName" column ="FirstName" ></ property > < property name ="LastName" column ="LastName" ></ property > </ composite-element > </ set > < property name ="BirthDay" type ="DateTime" ></ property > </ class > </ hibernate-mapping >
注意:Composite可以包含集合也可以不包含集合,上面这样的配置就不包括集合,映射的属性可以选择为List,map,bag,idbag 运行添加一个Composite的测试代码,会在数据库中建立两个数据表 CompositeUser和UserNames 效果图