Updating counters through Hibernate
Posted
by at
on Stack Overflow
See other posts from Stack Overflow
or by at
Published on 2010-05-25T20:14:16Z
Indexed on
2010/05/25
21:11 UTC
Read the original article
Hit count: 157
This is an extremely common situation, so I'm expecting a good solution. Basically we need to update counters in our tables. As an example a web page visit:
Web_Page
--------
Id
Url
Visit_Count
So in hibernate, we might have this code:
webPage.setVisitCount(webPage.getVisitCount()+1);
The problem there is reads in mysql by default don't pay attention to transactions. So a highly trafficked webpage will have inaccurate counts.
The way I'm used to doing this type of thing is simply call:
update Web_Page set Visit_Count=Visit_Count+1 where Id=12345;
I guess my question is, how do I do that in Hibernate? And secondly, how can I do an update like this in Hibernate which is a bit more complex?
update Web_Page wp set wp.Visit_Count=(select stats.Visits from Statistics stats where stats.Web_Page_Id=wp.Id) + 1 where Id=12345;
© Stack Overflow or respective owner