Use of NHibernate transactions:
Public voidAdd (Customer customer) {ISession session=_sessionmanager.getsession (); ITransaction Transaction = session. BeginTransaction (); Try{session. Save (customer); Session. Flush ();//clear first-level cache transaction.commit (); } Catch(Exception) { transaction. Rollback (); } finally{session. Close (); } }
Test:
[TestMethod] [ExpectedException (typeof(NHibernate.Exceptions.GenericADOException))] Public voidtestaddtransation () {customerservice customerservice=NewCustomerService (); OrderService OrderService=NewOrderService (); Customer Customer1=NewCustomer () {FirstName="Test", LastName="TestAddTransation1", Age=Ten }; Order Order1=NewOrder () {OrderDate= DateTime.Now.AddMinutes (1), Customer=Customer1}; Order Order2=NewOrder () {OrderDate= DateTime.Now.AddMinutes (2), Customer=Customer1}; Customer Customer2=NewCustomer () {FirstName=NULL,//database requirement cannot be null, now intentionally throwing an add exceptionLastName ="testaddtransation", Age=Ten }; Order Order3=NewOrder () {OrderDate= DateTime.Now.AddMinutes (3), Customer=Customer2}; Order Order4=NewOrder () {OrderDate= DateTime.Now.AddMinutes (4), Customer=Customer2}; Customer1. Orders.add (Order1); Customer1. Orders.add (ORDER2); Customer2. Orders.add (ORDER3); Customer2. Orders.add (ORDER4); Customerservice.add (Customer1); //Customer1 and its Order1 and Order2 can be successfully inserted because they are not in the same business as Customer2Customerservice.add (CUSTOMER2);//Customer2 Insert failed, Order3 and ORDER4 cannot be inserted successfully. Assert.isnull (Customerservice.get (customer1. CUSTOMERID)); Assert.isnull (Orderservice.find (order1. ORDERID)); Assert.isnull (Orderservice.find (order2. ORDERID)); }
-----------------------------------------------
About the addition of transactional operations:
Session. Flush ();//Clear first-level cache
Whether it will be saved to the database immediately
The conclusion is that the database will not be saved immediately, but wait until the call Transaction.commit () is actually saved to the database:
Graphic: