黑马程序员 2023JavaWeb 教程教学管理系统部门管理,员工管理功能实现笔记。

通过idea搭建具有三层架构的springboot项目

开发项目的三层架构
其中的Dao层用Mapper标识,构造出来的项目结构大体如下
在这里插入图片描述

准备工作

通过application.yml文件配置数据库连接以及mybatis

spring:
  #数据库连接信息
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.100.19:3306/tlias
    username: root
    password: ***********
#mybatis配置信息
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true

yml配置文件相较于properties的优点

在这里插入图片描述

根据接口文档分别实现功能

controller层:主要用于接收请求,响应数据

参数的传递

根据RESTful规范,前端传递过来的请求方式大概分为GET,POPST,PUT,DELETE等几种
在(只)接收这几种请求方式时候,对应几种不同的注解。

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
//这几个注解都加上了@RequestMapping注解

这几种,在这几个注解后面可以加括号指定访问路径,例如

@RequestMapping("/depts")

注解可以加在方法之前,也可以加在类之前。
加了这种注解的类可以简化方法的注解例如

@RestController
public class DeptController {

    //private static Logger log = LoggerFactory.getLogger(DeptController.class);

    //@RequestMapping(value = "/depts",method = RequestMethod.GET)
    /**
     * 查询部门
     */
    @Autowired
    private DeptService deptService;
    @GetMapping("depts/)
    public Result list(){
        log.info("查询全部部门的数据");
        List<Dept> deptList =  deptService.list();
        return Result.success(deptList);
    }
  }

可以简化为

//在类上面添加了@RequestMapping注解
@RequestMapping("/depts")
@RestController
public class DeptController {

    //private static Logger log = LoggerFactory.getLogger(DeptController.class);

    //@RequestMapping(value = "/depts",method = RequestMethod.GET)
    /**
     * 查询部门
     */
    @Autowired
    private DeptService deptService;
    @GetMapping
    public Result list(){
        log.info("查询全部部门的数据");
        List<Dept> deptList =  deptService.list();
        return Result.success(deptList);
    }
 }
接收前端发来的请求参数

前端发来的请求参数可以分为以下几种
1,无请求参数
2,路径参数 例如/depts/{id}
3,json格式的参数

在这里插入图片描述

接收路径参数示例代码

@DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        log.info("通过id删除部门:{}",id);
        deptService.delete(id);
        return Result.success();
    }

方法在接收参数里面使用了@PathVariable注解

在接收json参数,可以定义多个变量进行接收,

@GetMapping
    public Result page(String name, Short gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询,参数:{},{},{},{},{},{}", name, gender, begin, end, page, pageSize);
        PageBean pageBean = empService.page(name, gender, begin, end, page, pageSize);
        return Result.success(pageBean);
    }

@DateTimeFormat注解可以指定时间格式
需要注意的是,变量的名称必须和json中传递过来的参数一致。如果不一致的话,传递参数会失败。可以使用@RequestParam(“在此指定参数名称” Object object ),这个注解中还可以指定参数的默认值
在变量比较多的时候,我们还可以把变量封装成一个对象。
例如

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private Integer id; //ID
    private String username; //用户名
    private String password; //密码
    private String name; //姓名
    private Short gender; //性别 , 1 男, 2 女
    private String image; //图像url
    private Short job; //职位 , 1 班主任 , 2 讲师 , 3 学工主管 , 4 教研主管 , 5 咨询师
    private LocalDate entrydate; //入职日期
    private Integer deptId; //部门ID
    private LocalDateTime createTime; //创建时间
    private LocalDateTime updateTime; //修改时间
}

其中的@Data注解可以简化javabean的书写。
这样的话我们在前端传递参数过来的时候就可以用对象来接收。
在这里插入图片描述

@PostMapping
    public Result save(@RequestBody Emp emp){
        empService.addEmp(emp);
        return Result.success();
    }

在用对象接收数据的时候,需要加上@RequestBody注解

返回的参数 为了统一返回数据我们设计了一个专门的类进行返回数据
package com.itheima.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private Integer code;//响应码,1 代表成功; 0 代表失败
    private String msg;  //响应信息 描述字符串
    private Object data; //返回的数据

    //增删改 成功响应
    public static Result success(){
        return new Result(1,"success",null);
    }
    //查询 成功响应
    public static Result success(Object data){
        return new Result(1,"success",data);
    }
    //失败响应
    public static Result error(String msg){
        return new Result(0,msg,null);
    }
}

service:主要进行数据的逻辑处理

在service中,我们通常还要编写接口,同一实现类的规范,方便日后的处理逻辑的变更,再去实现这些接口。
在这里插入图片描述
在实现类中实现数据的逻辑处理。
在开发项目中,controller的方法会调用service层的类方法,如果直接在controller创建service层的对象会非常不方便,所以我们采用IoC(控制反转) 、DI(依赖注入)的方法。实现控制反转的话我们需要在需要控制反转的类前面加上@Component注解,加上这个注解就相当于把类交给容器去管理了。对于这个注解还有几种分类。

//在controller层的类,一般加上
@RestController
//在service层的类,一般加上
@Service
//在dao层的类,一般加上
@Mapper

所谓自动注入就是需要使用某个类的时候,不之间创建对象,而是加上@Autowired注解,例如

@Autowired
    EmpMapper empMapper;

这样就可以直接使用类中的方法。

mapper层主要是用于数据的访问,使用sql语言对数据库进行增删改查的功能

如果mapper层的方法需要使用的sql语句比较简单的话,可以使用注解的方式,例如

public interface DeptMapper {
    @Select("select * from dept")
    List<Dept> list();

    @Delete("delete from dept where id = #{id}")
    void delete(Integer id);

    @Insert("insert into dept (name, create_time, update_time) VALUES (#{name},#{createTime},#{updateTime})")
    void insert(Dept dept);

    @Update("update dept set name = #{name} , update_time=#{updateTime} where id =#{id} ")
    void update(Dept dept);

    @Select("select * from dept where id = #{id}")
    Dept selectById(Integer id);
}

如果遇到比较复杂的sql语句,就需要考虑使用mybatisx工具进行操作
如果一个类需要使用mybatis进行注解,我们就需要在resources包下在需要使用的类的同包名下创建.xml配置文件。
在这里插入图片描述
.xml配置文件的编写可以参考MyBatis中文网。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

在配置好.xml文件之后我们就可以在.xml文件中编写sql语句。

public interface EmpMapper {
    
    @Select("select * from emp")
    List<Emp> list();

    List<Emp> conditionalSelect(String name, Short gender, LocalDate begin, LocalDate end);

    void deleteByIds(List<Integer> ids);

    void addEmp(Emp emp);

    void update(Emp emp);

    Emp selectById(Integer id);
}
<?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.itheima.mapper.EmpMapper">
    <sql id="commentSelect">
        select id,
               username,
               password,
               name,
               gender,
               image,
               job,
               entrydate,
               dept_id,
               create_time,
               update_time
        from emp
    </sql>
    <insert id="addEmp">
        insert into emp (username, name, gender, image, job, entrydate, dept_id, create_time, update_time)
        VALUES (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})
    </insert>
    <update id="update">
        update emp
        set username=#{username},
            name=#{name},
            gender=#{gender},
            image=#{image},
            job=#{job},
            entrydate=#{entrydate},
            dept_id=#{deptId},
            create_time=#{createTime},
            update_time=#{updateTime}
        where id = #{id}
    </update>
    <delete id="deleteByIds">
        delete from emp
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>

    </delete>
    <select id="conditionalSelect" resultType="com.itheima.pojo.Emp">
        <include refid="commentSelect">
        </include>
        <where>
            <if test="name!=null and name != ''">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender!=null">
                and gender = #{gender}
            </if>
            <if test="begin!= null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>
    <select id="selectById" resultType="com.itheima.pojo.Emp">
        select id,
               username,
               password,
               name,
               gender,
               image,
               job,
               entrydate,
               dept_id,
               create_time,
               update_time
        from emp
        where id = #{id}
    </select>
</mapper>

值得注意的是.xml文件有三个约束,推荐使用MyBatisX插件一键生成。

动态sql语句
动态sql语句使用的比较多的有<if> <where> <set> <foreach> <sql><include>
<if>用于条件判断,条件生效语句生效
<where>用于优化<if>中的where语句,去除多余的and
<set><where>用法相似
<foreach>用于遍历,例子如下:
	<delete id="deleteByIds">
        delete from emp
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
<sql><include>配套出现,就像是java中的提取方法和使用方法。
连接阿里云oss进行文件的储存
package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 * @author 19667
 */
@Component
public class AliOSSUtils {
    @Autowired
    AliOSSProperties aliOSSProperties;
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String endpoint = aliOSSProperties.getEndpoint();
        String bucketName = aliOSSProperties.getBucketName();
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}

package com.itheima.utils;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * {@code @Author} 19667
 * {@code @create} 2024/7/31 15:34
 */
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliOSSProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}

其中的@ConfigurationProperties用于简化@Value注解

阿里云连接配置文件

aliyun:
  oss:
    endpoint: ******
    accessKeyId: ******
    accessKeySecret: ******
    bucketName: ******

#注解汇总

springboot注解大全

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值