Transactions in Castle ActiveRecord + NHibernate for dummies
I would like to do the following, all in a single atomic transaction:
- Read an object through ActiveRecord
- Save a new object through ActiveRecord
- Update another table via NHibernate开发者_Go百科
Also, if by the time I finish the transaction, the value of the object I've read in step 1 has changed, I would like the transaction to fail.
I've never used transactions before in either AR or NH, so please supply as much details as you can. How do the transaction mechanisms play together?
Well, Castle ActiveRecord depends on NHibernate. True, a Castle ActiveRecord Transaction class is not the same as the one found on NHibernate; but you should think of ActiveRecord's as a wrapper over the one in NHibernate.
So there is no need of "playing together". Because, deep down, they are the same.
Another important concept is that of "Session". A "session" is a unit of work, a "window" that you use to tell NHibernate what you want to do: queries, updates, inserts etc. Again, there is a NHibernate Session, and a Castle ActiveRecord Session too. Again, the latter is a wrapper over the first one.
This is important because when you're using a session in ActiveRecord (and in fact you always do, even if implicitly), it is possible to access the "hidden" NHibernate session inside it; usually using a delegate passed to the Execute method. And that's the way that you can use both styles of code inside your application (see the Execute Callback example here).
To get a better grasp of session meaning, see here.
Finally, I suggest that you always use ActiveRecord's style to declare sessions and transactions, even when mixing both styles of coding. Since they represent also NHibernate sessions and transactions, you are safe. To better understand that, please read here.
PS: Yep, I didn't write the example you asked for (too lazy for that), but I reckon it will be better for your learning process if you write it. Believe me, it's easier than you think.
Here's a quick start for a new project (created the last weeks)
https://github.com/haf/Castle.Facilities.NHibernate/wiki/NHibernate-Facility---Quick-Start
精彩评论