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

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?

Topics:

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}