赞
踩
多事务环境下如何保证数据库操作安全,常用的一种解决方案就是对操作数据表进行加锁处理。根据实现思路不同分:悲观锁与乐观锁2种。
悲观锁:悲观的认为多事务操作同一数据是及其不安全的,所以A事务在操作数据时,其他任何事务不允许对该数据进行修改,只能等待A事务操作结束后才可以执行。
乐观锁:乐观的认为A事务在操作数据时,期间不会有其他事务进行干扰,能顺利完成事务操作。
pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.7.2</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.example</groupId>
- <artifactId>mybatis-pluslgs</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>mybatis-pluslgs</name>
- <description>Demo project for Spring Boot</description>
- <properties>
- <java.version>8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- <dependency>-->
- <!-- <groupId>org.mybatis.spring.boot</groupId>-->
- <!-- <artifactId>mybatis-spring-boot-starter</artifactId>-->
- <!-- <version>3.0.0</version>-->
- <!-- </dependency>-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- </project>
添加配置类 开启乐观锁
MyBatis-Plus会自动讲乐观锁逻辑加载到sql中
使用Mybatis-Plus注意:
乐观锁支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime 仅支持 updateById(id) 与 update(entity, wrapper) 方法 另外,每次操作前都是先查询,替换,再更新,否则乐观锁无效
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。