mybatis-plus实现非法sql拦截(防止全表更新与删除)

文章目录

  • 什么是非法sql:
  • 拦截的意义是:
  • 使用:
    • 1、在pom文件中添加依赖
    • 2、注入MybatisPlusInterceptor类,并配置BlockAttackInnerInterceptor拦截器
  • 测试:

什么是非法sql:

不带where子句的delete和update,在生产环境中是不允许的。因为不带where子句的delete和update将会影响全表数据。这是非常可怕的!!

拦截的意义是:

就是阻止恶意的全表更新或删除

使用:

如果项目中还没添加mybatis-plus依赖:

		<dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.1.0version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-generatorartifactId>
            <version>3.1.0version>
        dependency>

1、在pom文件中添加依赖


        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-extensionartifactId>
            <version>3.5.1version>
        dependency>

2、注入MybatisPlusInterceptor类,并配置BlockAttackInnerInterceptor拦截器

@Configuration
public class MybatisPlusConfig {
  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
    return interceptor;
  }
}

测试:

数据库t_user表
mybatis-plus实现非法sql拦截(防止全表更新与删除)_第1张图片
实体类:

@TableName("t_user")
@Data
public class UserPO implements Serializable {

    @TableId(type = IdType.ASSIGN_ID)
    private Long id;

    private String userName;

    private String password;

    private String nickName;

    private int delFlag;


}

UserPOMapper:

@Mapper
public interface UserPOMapper extends BaseMapper<UserPO> {
}

IUserService:

public interface IUserService extends IService<UserPO> {
}

IUserServiceImpl:

@Service
public class IUserServiceImpl extends ServiceImpl<UserPOMapper, UserPO> implements IUserService {

}

Test:


	@Autowired
    private IUserService iUserService;
    
    @Test
    public void extension(){
        UserPO userPO = new UserPO();
        userPO.setUserName("yuan5");
        userPO.setPassword("123456");
        userPO.setNickName("bruce5");

        /**
         + SQL:UPDATE user  SET user_name=?,password=?,nick_name=?;
         */
        boolean b = iUserService.saveOrUpdate(userPO, null);
        System.out.println(b);
    }

**执行上面的测试方法,将抛出如下错误信息: **

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation
### The error may exist in com/example/demo/mapper/UserPOMapper.java (best guess)
### The error may involve com.example.demo.mapper.UserPOMapper.update
### The error occurred while executing an update
### Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation

上面的错误信息中,“Prohibition of table update operation” 禁止全表更新操作,这样就能阻止全表更新和删除操作。

你可能感兴趣的:(mybatis,sql,java,spring,boot)