在电商网站中,我们会上架很多商品,这些商品下架以后,我们如果将这些商品从数据库中删除,那么在年底统计商品的时候,这个商品要统计的,所以这个商品信息我们是不能删除的。
如果商城的商品下架了,这时候我们将商品从数据库删掉,那么到年终总结的时候,我们要总结这一年的销售额,发现少了20000,这肯定是不合理的。所以我们是不能将数据真实删除的。
1.修改字段
2.修改实体类
public class User extends Model<User> {
private Long id;
@TableField("username")
private String name;
private Integer age;
private String email;
@TableField("`desc`")
private String desc;
//逻辑删除字段
@TableLogic(value = "1",delval = "0")
private Integer status;
}
3.测试逻辑删除效果
@Test
void LogicDelete() {
userMapper.deleteById(7L);
}
4.查询t_user表
@Test
void logicSelect() {
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
List<User> users = userMapper.selectList(lambdaQueryWrapper);
System.out.println(users);
}
#配置逻辑删除字段
mybatis-plus.global-config.db-config.logic-delete-field=status
#未删除为1
mybatis-plus.global-config.db-config.logic-not-delete-value=1
#删除为0
mybatis-plus.global-config.db-config.logic-delete-value=0
1.添加字段
2.编写枚举类
public enum GenderEnum {
MAN(0,"男"),WOMEN(1,"女");
@EnumValue
private Integer gender;
private String genderName;
GenderEnum(Integer gender, String genderName) {
this.gender = gender;
this.genderName = genderName;
}
}
3.实体类添加相关字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User extends Model<User> {
private Long id;
private String name;
private Integer age;
private String email;
private GenderEnum gender;
private Integer status;
}
4.添加数据
@Test
void enumTest() {
User user = new User();
user.setName("王五");
user.setAge(28);
user.setEmail("[email protected]");
user.setStatus(1);
user.setGender(GenderEnum.WOMEN);
userMapper.insert(user);
}
1.在实体类中添加一个字段,Map类型
@Data
@NoArgsConstructor
@AllArgsConstructor
//查询时将json字符串封装为Map集合
@TableName(autoResultMap = true)
public class User extends Model<User> {
private Long id;
@TableField("username")
private String name;
private Integer age;
private String email;
@TableField("`desc`")
private String desc;
@TableField(exist = false)
private Integer online;
private Integer status;
private GenderEnum gender;
//指定字段类型处理器
@TableField(typeHandler = FastjsonTypeHandler.class)
private Map<String,String> contact;//联系方式
}
2.在数据库中添加一个字段contact,为varchar类型
3.添加依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.7version>
dependency>
4.测试添加操作
@Test
void typeHandler() {
User user = new User();
user.setName("Li");
user.setAge(28);
user.setEmail("[email protected]");
user.setGender(GenderEnum.MAN);
user.setStatus(1);
HashMap<String, String> map = new HashMap<>();
map.put("tel", "15896637666");
map.put("phone", "0371-60283366");
user.setContact(map);
userMapper.insert(user);
}
5.测试查询操作
@Test
void typeHandlerSelect() {
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
1.在数据库的表中添加两个字段
2.添加字段
//插入时自动填充createTime字段
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//插入或更新时自动填充updateTime字段
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3.编写自动填充处理器,指定填充策略
@Component
public class MyMetaHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
setFieldValByName("createTime",new Date(),metaObject);
setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
setFieldValByName("updateTime",new Date(),metaObject);
}
}
4.测试插入操作
@Test
void testFillInsert(){
User user = new User();
user.setName("wang");
user.setAge(35);
user.setEmail("[email protected]");
user.setGender(GenderEnum.MAN);
user.setStatus(1);
HashMap<String, String> contact = new HashMap<>();
contact.put("phone","010-1234567");
contact.put("tel","13388889999");
user.setContact(contact);
userMapper.insert(user);
}
5.测试更新操作
@Test
void testFillUpdate(){
User user = new User();
user.setId(18L);
user.setName("wangwu");
user.setAge(39);
user.setEmail("[email protected]");
user.setGender(GenderEnum.MAN);
user.setStatus(1);
HashMap<String, String> contact = new HashMap<>();
contact.put("phone","010-1234567");
contact.put("tel","13388889999");
userMapper.updateById(user);
}
1.注入MybatisPlusInterceptor类,并配置BlockAttackInnerInterceptor拦截器
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//防止全表更新
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
2.测试全表更新
@Test
public void updateAll(){
User user = new User();
user.setGender(GenderEnum.MAN);
userService.saveOrUpdate(user,null);
}
2.逆向工程
1.引入依赖,编写对应的配置文件信息
<dependencies>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.3.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.31version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
#配置数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=030522
2.使用IDEA连接mysql
4.编写逆向工程配置信息和生成信息
5.在Mapper接口上添加@Mapper注解
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
6.测试
@SpringBootTest
class Mp03ApplicationTests {
@Autowired
private UserMapper userMapper;
@Resource
private UserService userService;
@Test
void testUserMapper() {
List<User> users = userMapper.selectList(null);
users.forEach(user -> System.out.println(user));
}
@Test
void testUserService() {
User byId = userService.getById(10L);
System.out.println(byId);
}
}
3.常见需求代码生成
比如目前商品的库存只剩余1件了,这个时候有多个用户都想要购买这件商品,都发起了购买商品的请求,不能让多个用户都购买到,因为多个用户都买到了这件商品,那么就会出现超卖问题,库存不够是没法发货的。所以在开发中就要解决这种超卖的问题。
具体的SQL语句
Update 表 set 字段 = 新值,version = version + 1 where version = 1
乐观锁的使用
1.在数据库表中添加一个字段version,表示版本,默认值是1
2.找到实体类,添加对应的属性,并使用@Version标注为这是一个乐观锁字段信息
@Version
private Integer version;
3.配置拦截器
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//实现乐观锁的控制
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
4.测试效果
@Test
void updateTest() {
User user = userMapper.selectById(18L);
System.out.println(user);
user.setName("赵六");
userMapper.updateById(user);
}
5.模拟多个修改请求
@Test
void updateTest2() {
//模拟操作1的查询操作
User user1 = userMapper.selectById(18L);
System.out.println(user1);
//模拟操作2的查询操作
User user2 = userMapper.selectById(18L);
System.out.println(user2);
user2.setName("zhao");
userMapper.updateById(user2);
user1.setName("liu");
userMapper.updateById(user1);
}
1.引入依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.3version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.31version>
dependency>
2.编写代码生成器代码
@SpringBootTest
public class GeneratorApplicationTests {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false", "root", "030522")
.globalConfig(builder -> {
builder.author("hhb") // 设置作者
//.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D://"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.hhb.mp02") // 设置父包名
.moduleName("mybatisplus") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("t_user") // 设置需要生成的表名
.addTablePrefix("t"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
3.执行,查看生成效果
1.引入依赖
<dependency>
<groupId>p6spygroupId>
<artifactId>p6spyartifactId>
<version>3.9.1version>
dependency>
2.修改application.properties配置文件
#配置数据源
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatisplus?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=030522
3.在resources下,创建spy.properties配置文件
#3.2.1以上使用modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
4.测试
数据源切换
1.引入依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>dynamic-datasource-spring-boot-starterartifactId>
<version>3.1.0version>
dependency>
2.创建新的数据库,提供多数据源环境
3.编写配置文件,指定多数据源信息
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatisplus2?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
4.创建多个Service,分别使用@Ds注解描述不同的数据源信息
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}
@Service
@DS("slave_1")
public class UserServiceImpl2 extends ServiceImpl<UserMapper, User> implements UserService{
}
5.测试service多数据源环境执行结果
@SpringBootTest
class Mp03ApplicationTests {
@Autowired
private UserServiceImpl userServiceImpl;
@Autowired
private UserServiceImpl2 userServiceImpl2;
@Test
public void select(){
User user = userServiceImpl.getById(1L);
System.out.println(user);
}
@Test
public void select2(){
User user = userServiceImpl2.getById(1L);
System.out.println(user);
}
}