Spring Boot整合mybatis和SpringSecurity(安全)的使用教程

一:SpringBoot整合mybatis

本文使用的sql表:

create database springbootweb;

use springbootweb;

drop table if exists department;

create table department
(
    id    int primary key,
    dname varchar(20) not null
);

drop table if exists employee;

create table employee
(
    id       int primary key auto_increment,
    ename    varchar(50) not null,
    email    varchar(50),
    gender   int,
    birthday datetime,
    did      int references department (id)
);

insert into department(id, dname)
values (101, '教学部'),
       (102, '市场部'),
       (103, '教研部'),
       (104, '运营部'),
       (105, '后勤部');

insert into employee (ename, email, gender, birthday, did)
VALUES ('AA', '1234567@qq.com', 1, now(), 101),
       ('BB', '1234567@163.com', 0, now(), 102),
       ('CC', '4234335@qq.com', 1, now(), 103),
       ('DD', '4343343@qq.com', 0, now(), 104),
       ('EE', '6768554@qq.com', 1, now(), 105);

select e.id, e.ename, e.email, e.gender, e.birthday, dname
from employee e
         left join department d on d.id = e.did;

select *
from department;

1.注入依赖
mybatis的依赖可以前往maven查找springboot中mybatis的启动。

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

将此依赖包注入pom.xml文件中
2.再application.yaml文件中增加对mybatis的配置

mybatis:
  type-aliases-package: com.example.springboot.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

3.配置pojo层,写实体类,一张表对应一个实体类,写好所有的字段。
pojo层常用注解:
@Data : 注在类上,提供类的get、set、equals、hashCode、canEqual、toString方法
@AllArgsConstructor : 注在类上,提供类的全参构造
@NoArgsConstructor : 注在类上,提供类的无参构造
@Setter : 注在属性上,提供 set 方法
@Getter : 注在属性上,提供 get 方法
@EqualsAndHashCode : 注在类上,提供对应的 equals 和 hashCode 方法
@Log4j/@Slf4j : 注在类上,提供对应的 Logger 对象,变量名为 log

package com.example.springboot.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.annotation.Bean;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DePartment {
    private Integer id;

    private String dname;


}

4.配置mapper层
@Repository注解的作用使sptingboot可以识别出mapper,如果不加@Repository,可以再springboot的启动类中增加@MapperScan("com.example.springboot.mapper")

package com.example.springboot.mapper;

import com.example.springboot.pojo.DePartment;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface DePartmentMapper {

    List<DePartment> queryDePartmentList();

    DePartment queryDePartmentById(int id);

    int addDeParment(DePartment dePartment);

    int updateDePartment(DePartment dePartment);

    int deleteDeParment(DePartment dePartment);


}

5.mybatis中的mapper.xml文件中的配置
通用配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.springboot.mapper.DataExportMapper">
</mapper>

样例:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.springboot.mapper.DePartmentMapper">
    <select id="queryDePartmentList" resultType="DeParment">
        select *
        from deparment
    </select>

    <select id="queryDePartmentById" resultType="DePament">
        select * from deparment where id = #{id}
    </select>

    <insert id="addDeParment" parameterType="DeParment">
        insert into deparment (id,dname) values (#{id},#{dname})
    </insert>

    <update id="updateDePartment" parameterType="DeParment">
        update deparment set dname = #{dname} where id = #{id}
    </update>

    <delete id="deleteDeParment" parameterType="DeParment">
        delete from deparmnet where id = #{id}
    </delete>

</mapper>

6.配置Controller层接口
首先使用@Autowired自动装配mapper层的接口,可以直接进行调用interface接口中打方法。

package com.example.springboot.controller;

import com.example.springboot.mapper.DePartmentMapper;
import com.example.springboot.pojo.DePartment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DeParmentController {

    @Autowired
    private DePartmentMapper dePartmentMapper;

    @GetMapping("/queyDePartmentList")
    public  List<DePartment> queyDePartmentList(){
        List<DePartment> dePartments = dePartmentMapper.queryDePartmentList();
        return dePartments;
    }

    @GetMapping("/queryDePartmentById/{id}")
    public DePartment queryDePartmentById(@PathVariable("id") Integer id){
        DePartment dePartment = dePartmentMapper.queryDePartmentById(id);
        return dePartment;
    }

    @GetMapping("/addDeParment")
    public String addDeParment(){
        DePartment dePartment = new DePartment(3,"12");
        dePartmentMapper.addDeParment(dePartment);
        return "ok";
    }

    @GetMapping("/updateDePartment")
    public String updateDePartment(){
        DePartment dePartment = new DePartment(1, "3");
        int i = dePartmentMapper.updateDePartment(dePartment);
        return "update-ok";
    }

    @GetMapping("/deleteDeParment/{id}")
    public String deleteDeParment(@PathVariable("id") DePartment id){
        int i = dePartmentMapper.deleteDeParment(id);
        return "delete-ok";
    }
}

二:springsecurity使用

1.springsecurity的简介
springsecurity和shiro很像除了类不一样,名字不一样,springsecurity是针对spring项目的安全框架。也是springboot底层安全模块默认的技术选型,它可以实现强大的web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。

核心功能

  • 认证 (你是谁)
  • 授权(你可以做什么)
  • 防护(防止伪造身份)

2.springsecurity必记的类:

  • WebSecurityConfigurerAdpater:自定义Security策略
  • AuthenticationmanagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式 @Enable表示开启某个功能
    springsecurity的两个主要目标是:“认证”和“授权”(访问控制)
    “认证”(Authentication)
    “授权” (Authorization)
    3.注入依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>

3.代config层中配置

package com.example.springboot.Config;


import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;

@EnableWebFluxSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        //允许所有用户访问
                .antMatchers("/").permitAll()
                //只允许vip1访问
                .antMatchers("/form").hasAnyAuthority("vip1")
                .antMatchers("/chat").hasAnyAuthority("vip2")
                .antMatchers("/table").hasAnyAuthority("vip3");
    }
}

  • 13
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
Spring Security 是一个开源的安全框架,用于保护基于Spring框架构建的应用程序。MyBatis-Plus 是基于 MyBatis 的增强工具,用于简化 MyBatis 操作和提高开发效率。 将 Spring SecurityMyBatis-Plus 整合主要包括以下几个步骤: 1. 首先,在 Spring Boot 项目的 pom.xml 文件中添加 Spring SecurityMyBatis-Plus 的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>latest version</version> </dependency> ``` 2. 接下来,在项目的配置文件 application.properties 或 application.yml 中配置数据库连接和 MyBatis-Plus 的相关配置。 3. 创建一个用户实体类和对应的 Mapper 接口,使用 MyBatis-Plus 提供的注解和方法完成数据访问操作。 4. 创建一个自定义的 UserDetailsService 实现类,用于从数据库中获取用户信息,实现 loadUserByUsername 方法。 5. 创建一个自定义的 PasswordEncoder 实现类,用于加密和校验用户密码。 6. 配置 Spring Security,创建一个继承自 WebSecurityConfigurerAdapter 的类,并重写 configure 方法,设置用户认证规则、登录配置和访问控制规则。 7. 在 Spring Boot 启动类上使用 @MapperScan 注解,扫描 Mapper 接口。 通过以上步骤,就可以实现 Spring SecurityMyBatis-Plus 的整合。在实际应用中,还可以根据具体需求进行一些其他配置和扩展,例如添加角色权限控制、自定义登录页面和处理逻辑等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@黑夜中的一盏明灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值