Nhibernate order of SQL statements when flushing session

According to NHibernate documentation, SQL statements are issued in the following order when a session is flushed:

  • all entity insertions, in the same order the corresponding objects were saved using ISession.Save()
  • all entity updates
  • all collection deletions
  • all collection element deletions, updates and insertions
  • all collection insertions
  • all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete()
  • Why is it forced in this order and is there any way to change it so that the statements are executed in the same order that I give them?


    It's in that order because it's the safest.

    And no, you can't change the order. But also, you never gave NHibernate any order: you just mark entities for persistence; NHibernate determines what to do automatically.

    If you think you need more control over individual SQL operations, you can use IStatelessSession instead of a regular ISession . You lose all the stuff NH does automatically (lazy loading, caching, dirty-tracking), but you can (must) say explicitly when to Insert , Delete or Update a record.


    You can't change the order NHibernate generates SQL in per the above, but you can chunk up the units of work.

    eg:

    using(var transaction = Session.BeginTransaction())
    {
        var company = Session.QueryOver<Company>().First();
        var employee = new Employee{ ID = Guid.NewID() };
        company.Employees.Add(employee);
        Session.Flush();    
    
        var carSpace = new CarParkingSpace { EmployeeID = employee.ID };
        Session.Save(carSpace);
    
        transaction.Commit();
    }
    

    By adding the Session.Flush() - everything to that point will be pushed to the transaction. Without it, NHibernate would try to create a parking space allocated to a not yet existing employee.

    链接地址: http://www.djcxy.com/p/3984.html

    上一篇: 如何等待电子邮件意图完成并获得结果?

    下一篇: 刷新会话时,SQL语句的Nhibernate顺序