如何在Hibernate中执行原子操作?
你好
我有一个休眠实体,它有一组另一个实体作为其字段。像这样的事情:
public class UserEntity implements Srializable {
private Set<Role> roles;
}
我应该以一种至少有一个 ADMIN 用户始终存在于系统中的方式保留表。这可以通过简单的方式完成,如下所示:
public void updateUser{
UserEntity ue = getUser();
if (userIsNotTheLastAdmin(ue)) {
/** Here is a race condition **/
roles.remove(Role.ADMIN);
getSession().saveOrUpdate(ue);
}
}
但真正的问题发生在我们有并发操作时。如何以原子方式执行所有操作?
谢谢,
HM
Hi
I have a hibernate entity which has a set of another entity as its field. Something like this:
public class UserEntity implements Srializable {
private Set<Role> roles;
}
I should keep tables in a way that at least one ADMIN user always be exist in the system. This may be done in a simple way and can be like below:
public void updateUser{
UserEntity ue = getUser();
if (userIsNotTheLastAdmin(ue)) {
/** Here is a race condition **/
roles.remove(Role.ADMIN);
getSession().saveOrUpdate(ue);
}
}
But the real problem happens when we have concurrent operations. How can I perform all of the operation in an atomic way?
Thanks,
HM
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您可能不想锁定整个数据库表,这是一件非常邪恶的事情,所以您可以在组表中拥有一个带有 usercount 值的字段,然后您可以将事务跨越用户表操作和更新组表中相应的字段值,并确保特定组的用户计数不低于 1。由于 hibernate 自动获取更新的写锁,因此您不必考虑手动锁定策略,如下所述:http://docs.jboss.org/hibernate/core/3.3/参考/en/html/transactions.html#transactions-locking
希望有帮助..
since you probably dont want to lock a whole db table, which is quite an evil thing to do, you could have a field in your group table with a usercount value, then you can span your transactions over user table manipulations and the update of the corresponding field value in the group table and make sure that the usercount for specific groups does not drop below 1. since hibernate acquires write locks for updates automatically you wont have to think about manual locking strategies as described here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/transactions.html#transactions-locking
hope that helped..