这是一种极其常见的情况,所以我期待一个好的解决方案。基本上我们需要更新表中的计数器。以网页访问为例:
Web_Page
--------
Id
Url
Visit_Count
所以在 hibernate 状态下,我们可能会有这样的代码:
webPage.setVisitCount(webPage.getVisitCount()+1);
mysql存在read默认不关注事务的问题。因此,访问量大的网页的计数会不准确。
我习惯于做这种事情的方式就是调用:
update Web_Page set Visit_Count=Visit_Count+1 where Id=12345;
我想我的问题是,我如何在 Hibernate 中做到这一点?其次,我如何在稍微复杂一点的 Hibernate 中进行这样的更新?
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;
最佳答案
The problem there is reads in mysql by default don't pay attention to transactions. So a highly trafficked webpage will have inaccurate counts.
的确如此。我会在这里使用 DML 样式操作(请参阅第 13.4. DML-style operations 章):
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update webPage wp set wp.visitCount = wp.visitCount + 1 where wp.id = :id";
int updatedEntities = s.createQuery( hqlUpdate )
.setLong( "newName", 1234l )
.executeUpdate();
tx.commit();
session.close();
结果应该是
update Web_Page set Visit_Count=Visit_Count+1 where Id=12345;
And secondly, how can I do an update like this in Hibernate which is a bit more complex?
嗯...我很想说“你完蛋了”...需要考虑更多。
关于sql - 通过 Hibernate 更新计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908176/