sql - 通过 Hibernate 更新计数器

标签 sql mysql hibernate transactions counter

这是一种极其常见的情况,所以我期待一个好的解决方案。基本上我们需要更新表中的计数器。以网页访问为例:

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/

相关文章:

mysql - 关于优化多个联接的方法的建议。使用数据库触发器使用另一个表来编译数据是不好的做法吗?

mysql - 从用户表中选择用户名和从注释表中选择注释?

SQLite:如果存在则更新或使用来自不同表的选择进行插入

php - MySQL - 减少select语句中嵌套公式的长度

c# - 如何将对 DataTable 所做的更改提交到我从中获取它的表?

sql - 测试 MySQL 表中是否存在一行的最佳方法

java - Hibernate 查询与对象 id 列表匹配的对象列表

php - Jqgrid 分页由于查询而无法工作

java - Spring boot getOutputStream() 已被调用用于此响应

Spring:无法将 @Transactioanl 注释从 DAO 移动到服务层