Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

New Profiler Feature: Avoid Writes from Multiple Sessions In The Same Request

DZone's Guide to

New Profiler Feature: Avoid Writes from Multiple Sessions In The Same Request

· ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

Because I keep getting asked, this feature is available for the following profilers:

This new feature detects a very interesting bad practice, write to the database from multiple session in the same web request.

For example, consider the following code:

public void SaveAccount(Account account)
{
using(var session = sessionFactory.OpenSession())
using(session.BeginTransaction())
{
session.SaveOrUpdate(account);
session.Transaction.Commit();
}
}

public Account GetAccount(int id)
{
using(var session = sessionFactory.OpenSession())
{
return session.Get<Account>(id);
}
}

It is bad for several reasons, micro managing the session is just one of them, but the worst part is yet to come…

public void MakePayment(int fromAccount, int toAccount, decimal ammount)
{
var from = Dao.GetAccount(fromAccount);
var to = Dao.GetAccount(toAccount);
from.Total -= amount;
to.Total += amount;
Dao.SaveAccount(from);
Dao.SaveAccount(to);
}

Do you see the error here? There are actually several, let me count them:

  • We are using 4 different connections to the database in a single method.
  • We don’t have transactional safety!!!!

Think about it, if the server crashed between the fifth and sixth lines of this method, where would we be?

We would be in that wonderful land where money disappear into thin air and we stare at that lovely lawsuit folder and then jump from a high window to a stormy sea.

Or, of course, you could use the profiler, which will tell you that you are doing something which should be avoided:

image

Isn’t that better than swimming with the sharks?

Do you pay to use your database? What if your database paid you? Learn more with RavenDB.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}