mybatis_plus通用枚举_配置多数据源_乐观锁
作者:互联网
A、创建数据库db1
创建用户表
字段 |
中文 |
类型 |
长度 |
主键 |
自增 |
备注 |
Id |
|
Bigint |
19 |
Y |
F |
使用雪花算法主键 |
Name |
用户名 |
Varchar |
|
|
|
|
Password |
密码 |
Varchar |
|
|
|
|
Status |
状态 |
|
|
|
|
0激活 1未激活 |
Create_time |
注册时间 |
|
|
|
|
|
update_time |
更新信息时间 |
|
|
|
|
|
使用Service完成用户表的功能测试
一、新增用户
1、ID使用雪花算法生成的主键
2、状态使用枚举类型
3、注册时间和更新信息时间使用自动填充
二、查询全部用户,密码不做回显
三、
使用ActiveRecord方式,完成用户表的修改功能测试
B、创建数据库db2
创建用户帐户表
字段 |
中文 |
类型 |
长度 |
主键 |
自增 |
备注 |
Id |
|
Bigint |
19 |
Y |
F |
使用雪花算法主键 |
Name |
用户名 |
Varchar |
|
|
|
|
Balance |
余额 |
int |
|
|
|
|
version |
版本 |
|
|
|
|
|
配置动态数据源
在db2库中,完成对用户帐户表信息的修改,要求使用乐观锁插件配置
在pom.xml里导入多数据源依赖,
同时插入配置避免项目出错影响正常编译执行
There are test failures
参考链接https://blog.csdn.net/u011134399/article/details/79103093
<?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> <groupId>com.xzit</groupId> <artifactId>day5_job</artifactId> <version>0.0.1-SNAPSHOT</version> <name>day5_job</name> <description>day5_job</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.3.7.RELEASE</spring-boot.version> </properties> <dependencies> <!--spring web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--junit--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--多数据源--> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.5.1</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.7.RELEASE</version> <configuration> <mainClass>com.xzit.Day5JobApplication</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <!--项目有错误时时仍正常编译运行,避免出现There are test failures报错--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> </plugins> </build> </project>
先创建一个枚举类
package com.xzit.enums; import com.baomidou.mybatisplus.annotation.IEnum; public enum StatusEnum implements IEnum<Integer> { UNACTIVE(0,"未激活"), ACTIVE(1,"激活"); StatusEnum(Integer statusValue,String statusDesc){ this.statusValue = statusValue; this.statusDesc = statusDesc; } private final Integer statusValue; private final String statusDesc; public String toString(){ return this.statusDesc; } @Override public Integer getValue() { return this.statusValue; } }
在application.yml里加上枚举类的全局配置,顺便把动态数据源也配置了,搞两个数据库连接上去,db1和db2
spring: datasource: # driver-class-name: com.mysql.cj.jdbc.Driver # url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8 # username: root # password: zengyu1234 dynamic: primary: db1 #设置默认的数据源或者数据源组,默认值即为master strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 datasource: db1: url: jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8 username: root password: zengyu1234 db2: url: jdbc:mysql://localhost:3306/db2?serverTimezone=GMT%2B8 username: root password: zengyu1234 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: #配置数据库逻辑删除的字段 # logic-delete-value: 1 # 逻辑已删除值(默认为 1) # logic-not-delete-value: 0 # 逻辑未删除值(默认为 0) db-config: logic-delete-field: deleted #配置主键id全局生成方式,遵循就近原则,比如方法中定义为雪花算法,则以方法为准 id-type: auto type-enums-package: com.xzit.enums
创建User实体类,使用注解声明id使用雪花算法生产,状态使用枚举类型,注册时间和更新时间自动填充,并且声明密码查询不返回结果
package com.xzit.entity; import com.baomidou.mybatisplus.annotation.*; import com.xzit.enums.StatusEnum; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.math.BigInteger; import java.time.LocalDateTime; @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) @TableName("user") public class User { //1、ID使用雪花算法生成的主键 @TableId(type = IdType.ASSIGN_ID) private Long id; private String name; //声明该密码字段查询不返回值 //二、查询全部用户,密码不做回显 @TableField(select = false) private String password; //创建并使用枚举类型 private StatusEnum status; //3、注册时间和更新信息时间使用自动填充 @TableField(fill = FieldFill.INSERT) private LocalDateTime create_time; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime update_time; }
创建一个config包和config类,引入自动填充功能的配置,不做这个的话自动填充功能无法使用,注意create_time这个名字要和实体类里的字段名匹配
package com.xzit.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.time.LocalDateTime; @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { //在插入时完成自动填充功能 this.strictInsertFill(metaObject, "create_time", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐) this.strictInsertFill(metaObject, "update_time", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐) } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "update_time", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐) } }
新建一个mapper接口继承baseMapper
package com.xzit.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xzit.entity.User; public interface UserMapper extends BaseMapper<User> { }
新建一个service接口类继承IService
package com.xzit.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xzit.entity.User; public interface UserService extends IService<User> { }
创建一个service接口的实现类,用@DS注解,声明他用的是db1这个数据源,连接到db1这个数据库去查数据,同时要继承ServiceImpl这个方法,泛型加入mapper类和实体类,这样就实现了所有基本的方法,省去了一堆实现UserService必须要写的CRUD方法代码。create增,delete删,update改,read查
package com.xzit.service; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xzit.entity.User; import com.xzit.mapper.UserMapper; import org.springframework.stereotype.Service; @Service @DS("db1") public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }
编写测试类,实现功能
新增用户,
查询全部用户,密码不做回显
package com.xzit; import com.xzit.entity.User; import com.xzit.enums.StatusEnum; import com.xzit.mapper.UserMapper; import com.xzit.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; @SpringBootTest public class Day7JobTest { @Resource private UserService service; /** * 新增数据 */ @Test public void testSave(){ User user = new User(); user.setName("伊万").setPassword("1234").setStatus(StatusEnum.ACTIVE); boolean b = service.save(user); System.out.println(b); } /** * 查询全部数据 */ @Test public void testSelect(){ List<User> list = service.list(); list.forEach(System.out::println); } }
执行结果
实体类继承Model即可实现ActiveRecord进行CRUD操作
package com.xzit.entity; import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.xzit.enums.StatusEnum; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.math.BigInteger; import java.time.LocalDateTime; @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) @TableName("user") public class User extends Model<User> { //1、ID使用雪花算法生成的主键 @TableId(type = IdType.ASSIGN_ID) private Long id; private String name; //声明该密码字段查询不返回值 //二、查询全部用户,密码不做回显 @TableField(select = false) private String password; //创建并使用枚举类型 private StatusEnum status; //3、注册时间和更新信息时间使用自动填充 @TableField(fill = FieldFill.INSERT) private LocalDateTime create_time; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime update_time; }
编写测试类测试:
package com.xzit; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.xzit.entity.User; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class Day7JobTestActiveRecord { @Test public void update(){ User user = new User(); user.setName("安东").setPassword("abcd"); UpdateWrapper wrapper=new UpdateWrapper(); wrapper.eq("name","伊万"); user.update(wrapper); } }
执行效果:
配置一个MybatisPlus的config文件,加入乐观锁插件
package com.xzit.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { /** * MybatisPlus拦截器 * @return */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //加入分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2)); //加入乐观锁插件 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } }
创建对应数据库表的实体类,在version字段上加上注解
package com.xzit.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.Version; import lombok.Data; @Data public class useraccount { @TableId(type = IdType.AUTO) private Integer id; private String name; private Integer balance; @Version private Integer version; }
创建测试类,添加断点进行测试
package com.xzit; import com.xzit.entity.Useraccount; import com.xzit.mapper.UseraccountMapper; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; @SpringBootTest public class Day7JobTestLock { @Resource private UseraccountMapper mapper; /** * 测试中,使用断点调试,在useraccount.setBalance()时,在数据库中手动修改了version,本次操作失败 */ @Test public void testUpdate(){ Useraccount useraccount = mapper.selectById(1); useraccount.setBalance(useraccount.getBalance()+500);//在此处添加断点 mapper.updateById(useraccount); } }
标签:数据源,baomidou,xzit,private,plus,mybatis,import,com,public 来源: https://www.cnblogs.com/zengyu1234/p/16667517.html