NHibernate事务提交后会将什么内容提交至数据库?

3

I have following code:

using (var session = SessionFactory.OpenSession())
{
  var entity = session.Get<Entity>(id);
  entity.Property1 = "new value";
  using (var tx = session.BeginTransaction())
  {
    entity.Property2 = "new value";
    tx.Commit();
  }
}

现在,我有些困惑,当执行 tx.Commit() 时,哪些内容会被提交到数据库呢? 只有事务范围部分的 Property2 会被提交,还是 Property1Property2 都会被提交?

2个回答

3

当您对持久对象进行更改时,这些更改将在会话刷新时发送到数据库,并提交事务将刷新会话。请注意,在某些情况下,会话可能会自动刷新,例如在使用数据库生成的标识符或发出查询时。

NHibernate中的事务块可以仅包含提交操作,这会让人感到困惑。为了提高可读性,我会将其改写为:

using (var session = SessionFactory.OpenSession())
{
  using (var tx = session.BeginTransaction())
  {
      var entity = session.Get<Entity>(id);
      entity.Property1 = "new value";
      entity.Property2 = "new value";
      tx.Commit();
  }
}

感谢您耐心的回答,我还有一个问题。ISession.Flush()ITransaction.Commit()之间有什么区别?它们都可以将数据同步到数据库,但使用ITransaction必须在提交之前开始它,而ISession.BeginTransaction()是一个令人困惑的操作,因为会提交会话中的所有更改,但不会提交事务范围内的更改(从BeginTransaction()Commit())。 - JasonMing
2
文档已经很好地解释了:http://nhforge.org/doc/nh/en/index.html#manipulatingdata。我的建议是将会话的FlushMode设置为Commit并使用事务。 - Jamie Ide

0

所有实体的属性都将被提交。在您的配置中,您可以设置一个选项,将 SQL 输出到控制台,您可以看到每次提交发送的查询。


哦,所以是从会话打开提交更改而不是事务开始提交? - JasonMing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接