在Spring框架mySQL上访问和更新数据遇到问题,想请教大家最高效的锁定TABLE行的方法。
假设我有两个表:一个记录所有圆圈及其 ID 和位置,另一个记录所有具有相同列的正方形。每个圆圈的位置都可以独立修改,正方形也是如此。但是也可以通过移动圆圈的位置来调整正方形的位置。伪代码如下:
Public ShapeMovingService{
@Transaction (isolation=required)
public moveCirclePosition(int id, int newPosition){
//move circle=id to a new position
//also move the square which relates to this circle accordingly
}
@Transaction (isolation=required)
public moveSquarePosition(int id, int newPosition){
//move square=id to a new position
}
}
public CircleDao extends JdbcTemplateSupport{
public updatePosition(int id, int position){
//query a circle from circle TABLE with id
//update the position of the circle
//ALSO: modify the position of the square which relates to this circle
}
}
public SquareDao extends JdbcTemplateSupport{
public updatePosition(int id, int position){
//query a square from squareTABLE with id
//update the position of the square
}
}
我创建了几个线程来完成以下任务:
- 两个线程不断更新圆圈id=1的位置
- 一个线程不断更新圆id=2的位置
- 一个线程不断更新方 block id=1的位置
- 一个线程不断更新方 block id=2的位置
移动id=2的圆的位置会影响id=1的方 block 的位置; circle id=1 与其他方 block 没有关系,square id=2 也没有。
我的问题是,我应该在什么时候锁定数据库操作,通过事务注释或同步关键字,这样就不会发生数据损坏?然而,不同的圈子仍然可以同时更新。现在我锁定了 updatePosition 函数,但这意味着一次只能更新一个圆/正方形。
感谢您的任何建议。
最佳答案
您可以探索 hibernate version-type 字段,它可以解决目的,如果您不使用 hibernate,则可以考虑将其实现为您的 base dao 的一部分。
如果您需要详细信息,请告知。
关于mysql - 如何在Spring中同步数据库访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754600/