代码改变世界

NHibernate Beginner ch5

2011-07-04 18:20  一一九九  阅读(324)  评论(0编辑  收藏  举报

Using what we have already learned, NHibernate knows enough about our data structure and our objects. now it’s time to let NHibernate connect to the database.  Think of an NHibernate session as an abstract or virtual conduit to the database . with NHibernate , we ask the sessionFactory for a session object , and that’s it.

通过NHibernat连接到数据库大体上需要通过以下过程:

Configuration cfg = new Configuration();
cfg.Properties.Add(NHibernate.Cfg.Environment.ConnectionProvider,
typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName);
cfg.Properties.Add(NHibernate.Cfg.Environment.Dialect,
typeof(NHibernate.Dialect.MsSql2005Dialect).AssemblyQualifiedName);
cfg.Properties.Add(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass,
typeof(NHibernate.ByteCode.LinFu.ProxyFactoryFactory).AssemblyQualifiedName);
cfg.AddAssembly(
typeof(Address).AssemblyQualifiedName);

todo: ProxyFactoryFactory 这个东西是干嘛用的?

todo: 了解这句话为啥不可以“cfg.AddAssembly(typeof(Address).AssemblyQualifiedName);”,而直接采用cfg.AddAssembly(“Ordering.Data”)就可以?另外采用cfg.AddAssembly(Assembly.GetAssembly(typeof(Address)));也是可以的

tips:
        error: Duplicate class/entity mapping…XXXXXXXXXX
         解决方案: google了一下发现这个问题出现的原因不禁相同,有的是AddAssembly多次,有的是配置重复。我这次出现的问题的原因就是Copy了一份配置结果没有修改类名称导致的。这也是hbm.xml的坏处,冗余造成错误。

todo: abstract factory pattern http://en.wikipedia.org/wiki/abstract_factory_pattern

todo: 为什么property should by virtual or override?

tips:
        error: could not get or update next value
        解决方案: 由于ID采用的是hilo的方式,需要在数据库中配置默认的数据库和键值。
hilo

uses a hi/lo algorithm to efficiently generate identifiers of any integral type, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with a user-supplied connection.

You can use the "where" parameter to specify the row to use in a table. This is useful if you want to use a single tabel for your identifiers, with different rows for each table.

create table hibernate_unique_key(next_hi int)
insert  hibernate_unique_key(next_hi) values( 10001)

hilo的算法还是比较牛的,只需要一个next_hi的值,同时开六个client,生成6万多条记录,居然没有重复值生成。

todo:  了解一下hilo方式的键值生成。 这个需要在数据库中创建一张表,简要的看了一下是通过下面的语句进行段号的获取的

select next_hi from hibernate_unique_key with (updlock, rowlock), 看来和数据库的关联还是比较大。另外当批量生成Object的时候,Nhibernate 是生成了一条条的语句执行的。 另外NH的Save方法居然没有批量生成的参数,比如说我传入一个Object的List啥的。