首先介绍一下框架结构(这个有个概念就可以);

然后我们会介绍一个很重要的概念(一定要好看)!!

这节对 NHibernate 架构做一个介绍,首先要了解一下该框架在应用程序中的位置:

先来一个简单的图:

3. NHibernate基础知识 - 你必须知道的一些事情-LMLPHP

正如你看见的一样,NHibernate 处于应用程序和数据库中间,作用呢?举个例子:

NHibernate 就好比图书馆的管理员,无论你借书还是还书,只需要告诉管理员,管理员把剩下的事都替你解决了。

再来一张详细点的图:

3. NHibernate基础知识 - 你必须知道的一些事情-LMLPHP

这个图简单的说,能看出来,NHibernate中有两个“组件”,Session和SessionFactory,以后我们会详细介绍,这里简单介绍一下:每个Session对应一次对数据库的操作,也就是说,当你需要操作数据库的时候,就需要获取一个Session对象,Session封装了操作数据库的上下文,而且Session不是线程安全的;SessionFactory是生成Session的工厂,每一个SessionFactory对应一个数据库,所以并不建议你实例化对个SessionFactory对象,这个是线程安全的(我们建议针对每一个数据库,采用单例方式实现 -- 像我们的Demo)。

最后来一个复杂的图:

3. NHibernate基础知识 - 你必须知道的一些事情-LMLPHP

还记得Demo中定义的hibernate.hbm.xml吗?

通过配置该配置文件, 可以操作不同类型的数据库。

接下来我们介绍一个重要的概念!!!!!

一个对象在NHibernate框架中有三种状态:transient、persistent和detached,分别介绍:

--- Transient:瞬时状态,就是短暂的临时的

[官方解释]

The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).

[个人理解]

new 一个类,这个类从来没有被持久化过,即创建一个类后,尚未与NHibernate关联的对象,简单理解,就是你 new 了一个新类。当然你可以通过ISession 把这个类变成持久类。

--- Persistent:持久的状态,就是永久的

[官方解释]

The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, NHibernate guarantees that persistent identity is equivalent to CLR identity (in-memory location of the object).

[个人理解]

如果你理解了Transient状态,那就简单多了,持久类就是该类在数据库中有对应的记录,也许是刚通过Session保存到数据库中或者刚刚被读取出来,总之就是还没有关系该ISession对象,如果你此时修改该对象,那么会直接反应到数据库中,和Silverlight中的双向操作类似。

--- Detached:分离的状态,断开的分开的

[官方解释] The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database. Fordetached instances, NHibernate makes no guarantees about the relationship between persistent identity and CLR identity.

[个人理解]

当持久类关联的ISession关闭后,该对象即从持久状态变成了分离状态,其实挺好理解的吧。

这三个状态其实挺重要的,只有你理解了这三个状态,在之后的学习中才会觉得很轻松。

04-21 04:29