在数据库并发操作时,为了保证数据的正确性,我们会做一些并发处理,主要就是加锁。在加锁的选择上,有几种方式,悲观锁,乐观锁。
悲观锁,简单的理解就是把需要的数据全部加锁,在事务提交之前,这些数据全部不可读取和修改。
乐观锁,使用对数据进行版本校验和比较,来对保证本次的更新时最新的,否则就失败。
悲观锁的做法:
select * from user where uid=1 for update;
update user set name='bac' where uid=1;
这样,uid为1的这行记录,就被锁住,在事务提交之前,他不可被其他事务读取和修改。
乐观锁的做法:
select uid,name,version from user where uid=1;
假设本次查询version=1,在更新操作时,
update user set name='abc', version=version+1 where uid=1 and version=1
这样,当其他事务在本次事务提交之前更新了,version就会+1,就不是刚才查询到的1,本次update 就失败。
在JPA中,我们可以使用@Version在某个字段上进行乐观锁控制。
@Entity
@Table(name = "data_version")
public class DataVersion extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 1830796806342370927L;
private String name;
private int age;
@Version
private Long version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public String toString() {
return "DataVersion [name=" + name + ", age=" + age + ", version=" + version + "]";
}
}
@DataJpaTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Core.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class JpaTest {
@Autowired
DataVersionJpaRepository jpa;
@Test
public void test() {
DataVersion d = new DataVersion();
d.setName("hello");
d.setAge(27);
d = jpa.saveAndFlush(d);
Long id = d.getId();
System.out.println(id);
DataVersion d2 = jpa.findOne(id);
d2.setAge(26);
d2 = jpa.saveAndFlush(d2);
System.out.println(d2);
}
}
Hibernate: insert into data_version (enable, age, name, version) values (?, ?, ?, ?)
21
Hibernate: update data_version set enable=?, age=?, name=?, version=? where id=? and version=?
DataVersion [name=hello, age=26, version=1]
当乐观锁更新失败的时候,会抛出异常org.springframework.orm.ObjectOptimisticLockingFailureException
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@SpringBootTest(classes = AccountsApplication.class)
public class JpaTest {
@Autowired
DataVersionJpaRepository jpa;
@Test
public void test() throws InterruptedException {
DataVersion d = new DataVersion();
d.setName("hello");
d.setAge(27);
d = jpa.saveAndFlush(d);
Long id = d.getId();
System.out.println(id);
DataVersion d2 = jpa.findOne(id);
d2.setAge(26);
new Thread(new Runnable() {
@Override
public void run() {
DataVersion d2 = jpa.findOne(id);
d2.setAge(99);
d2 = jpa.saveAndFlush(d2);
System.out.println("th:" + d2);
}
}).start();
Thread.sleep(5000);
d2 = jpa.saveAndFlush(d2);
System.out.println(d2);
Thread.sleep(20000);
}
}