NHibernate Transactions on Reads

后端 未结 5 1000
清酒与你
清酒与你 2020-12-14 01:34

I have read the documentation and explanation on why it is highly recommended to use transactions on read operations in NH. However, I still haven\'t totally \"bought\" into

5条回答
  •  忘掉有多难
    2020-12-14 02:07

    Let's focus on what happens if you would not use transactions. It's customary, but not mandatory, that you close the Session at the end of processing, but before you start reading the data (i.e., the View). This method is propagated under the term "Open Session in View" (though it obviously has a pattern for preventing read before close). This pattern is often used in web application where the session is opened when the request arrives and closed just before writing to the response stream.

    (N)Hibernate needs a session and a transaction. When you read without using an explicit transaction, the transaction will be setup for you. When you read after a transaction is committed, the behavior depends on NH configuration and driver.

    Both ODBC and JDBC do not define what happens when a connection is closed and there's uncommitted or unrollbacked data. When the connection is reopened, it is possible that a new transaction is automatically started.

    Using non-transactional access can only be used together with setting auto-commit explicitly in the NHibernate configuration. If not, the default of the driver is used and it may work, or may not work.

    In short, there are many shortcomings and undefined behaviors when you do not use transactions on reads. It will work often, but this depends on the configuration, the applied patterns, the drivers. There's a large chance you get LazyInitializationExceptions, which is a common result of read after commit without opening a new transaction.

    The "best practice" is to use one transaction for read/write and one other for read-only. This is described briefly in the previous link, section "Can I use two transactions in a session" but requires more of your implementation.

    It is not only "use transactions for read", it is also: "use the same transaction you use for writing for reading". (and then, while this is true, actual application will depend on your current patterns, how many tiers there are, caching and configuration).

    Update: expanded a bit, removed some ambiguities

提交回复
热议问题