什么是乐观锁
乐观锁顾名思义:他表示的就是乐观,面对任何事情都用积极乐观的心态去处理,首先她回认为你是安全的,然后去执行,如果当他发现不正确,那么他会立刻返回错误信息,嘿嘿
@Version
@version是什么
@version他是用于版本控制的,一般是hibernate的jpa使用,每当数据更新的时候,数据库中的@version就会更新状态,自增加一
@version如何使用
@version.正因为@version有这样的功能,所以我们高并发的,可以根据@version的版本号来查看是否是我们需要的版本,来避免高并发的时候出现脏读,如果@version发现数据不一致的时候他就会抛出一个错误码(一会你可以看见)
正常写法
@GetMapping("/judy.html")
public ProductInfoCategoryEntity productFindOne(){
ProductInfoCategoryEntity productInfoCategoryEntity = new ProductInfoCategoryEntity();
ProductInfoCategoryEntity productInfoServiceById = productInfoService.findById(3);
productInfoServiceById.setProductName("薯条");
productInfoService.save(productInfoServiceById);
return productInfoServiceById;
}
多线程下,主线程和从线程从乐观角度分析
@GetMapping("judy2.html")
public String ThreadTest() throws InterruptedException {
ProductInfoCategoryEntity productInfoServiceById = productInfoService.findById(2);
productInfoServiceById.setProductName("冰淇淋");
new Thread(new Runnable() {
@Override
public void run() {
ProductInfoCategoryEntity productInfoServiceById = productInfoService.findById(2);
productInfoServiceById.setProductName("巧克力");
productInfoService.save(productInfoServiceById);
}
}).start();
Thread.sleep(10000);
productInfoService.save(productInfoServiceById);
return "is judy";
}
出现错误,出现这个错误的原因是因为主线程在运行的时候一个新的线程过来,导致先执行新的线程,但是这个时候,执行完之后version++,但是对于主线程来说version并不知道++.所以当主线程最终要++的时候发现他变了,所以报错了.(有一行数据已经被另一个事物更改,所以映射失败)
{
“timestamp”: “2019-01-15T23:52:49.097+0000”,
“status”: 500,
“error”: “Internal Server Error”,
“message”: “Object of class [com.judy.demo.Entity.ProductInfoCategoryEntity] with identifier [2]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.judy.demo.Entity.ProductInfoCategoryEntity#2]”,
“path”: “/sell/Xu/Demo/judy2.html”
}
总结
不断成长哦,感谢徐 X X 的知识共享~