controller
DeptController
package com.itheima.controller;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
// private static Logger log = LoggerFactory.getLogger(DeptController.class);
/**
* 查询部门数据
*
* @return
*/
/*@RequestMapping(value = "/depts",method = RequestMethod.GET) // 指定请求方式为GET*/
@GetMapping
public Result list() {
log.info("查询全部部门数据");
// 调用Service来查询数据
List<Dept> deptList = deptService.list();
return Result.success(deptList);
}
/**
* 根据id删除部门
*
* @return
*/
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
log.info("根据id删除部门:{}", id);
//调用Service删除部门
deptService.delete(id);
return Result.success();
}
/**
* 新增部门
*
* @return
*/
@PostMapping
public Result add(@RequestBody Dept dept) {
log.info("新增部门:{}", dept);
deptService.add(dept);
return Result.success();
}
@GetMapping("/{id}")
public Result update(@PathVariable Integer id) {
log.info("修改部门id:{}", id);
Dept dept = deptService.getById(id);
return Result.success(dept);
}
@PutMapping
public Result update(@RequestBody Dept dept) {
log.info("修改部门:{}", dept);
deptService.update(dept);
return Result.success();
}
}
EmpController
package com.itheima.controller;
import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.regex.Pattern;
@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
@Autowired
private EmpService empService;
/**
* 批量查询
* @param page
* @param pageSize
* @param name
* @param gender
* @param begin
* @param end
* @return
*/
@GetMapping
public Result page(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer pageSize,
String name, Short gender,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
log.info("分页查询,参数:{},{},{},{},{},{}", page, pageSize, name, gender, begin, end);
//调用Service分页查询
PageBean pageBean = empService.page(page, pageSize, name, gender, begin, end);
return Result.success(pageBean);
}
/**
* 批量查询
* @param ids
* @return
*/
@DeleteMapping("/{ids}")
public Result delete(@PathVariable List<Integer> ids) {
log.info("批量删除操作:ids:{}", ids);
empService.delete(ids);
return Result.success();
}
/**
* 新增员工
* @return
*/
@PostMapping
public Result save(@RequestBody Emp emp) {
log.info("新增员工:,emp: {}", emp);
empService.save(emp);
return Result.success();
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
log.info("根据id来查询员工信息:{}", id);
Emp emp = empService.getById(id);
return Result.success(emp);
}
@PutMapping
public Result update(@RequestBody Emp emp) {
log.info("修改员工信息: {}", emp);
empService.update(emp);
return Result.success();
}
}
UploadController
package com.itheima.controller;
import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
public class UploadController {
@Autowired
private AliOSSUtils aliOSSUtils;
// 本地存储文件
/*@PostMapping("/upload")
public Result upload(String username, Integer age, MultipartFile image) throws IOException {
log.info("文件上传: {}, {}, {}", username, age, image);
// 获取原始文件名 - 1.jpg 123.0.0 jpg
String originalFilename = image.getOriginalFilename();
//构造唯一文件名(不能重复) --uuid(通用唯一识别码)7735c46e-efc3-4550-9d27-33ec992870d3
int index = originalFilename.lastIndexOf(".");
String extname = originalFilename.substring(index);
String newFileName = UUID.randomUUID().toString() + extname;
log.info("新的文件名: {}", newFileName);
// 将文件存储在服务器的磁盘目录中 C:\Users\27527\Desktop\image
image.transferTo(new File("C:\\Users\\27527\\Desktop\\image\\" + newFileName));
return Result.success();
}*/
@PostMapping("/upload")
public Result upload(MultipartFile image) throws IOException {
log.info("文件上传,文件名:{}", image.getOriginalFilename());
// 调用阿里云OSS工具类进行文件上传
String url = aliOSSUtils.upload(image);
log.info("文件上传完成,文件访问的url为: {}", url);
return Result.success(url);
}
}
mapper
DeptMapper
package com.itheima.mapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import org.apache.ibatis.annotations.*;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Mapper
public interface DeptMapper {
@Select("select * from tlias.dept")
List<Dept> list();
/**
* 根据id删除部门
*/
@Delete("delete from tlias.dept where id = #{id}")
void deleteById(Integer id);
/**
* 新增部门信息
*
* @param dept
*/
@Insert("insert into tlias.dept(name, create_time, update_time) values(#{name}, #{createTime}, #{updateTime})")
void insert(Dept dept);
/**
* 根据id查询部门
* @param id
* @return
*/
@Select("select * from dept where id = #{id};")
Dept getById(Integer id);
@Update("update tlias.dept set name = #{name}, update_time = #{updateTime} where id = #{id}")
void update(Dept dept);
}
EmpMapper
package com.itheima.mapper;
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDate;
import java.util.List;
@Mapper
public interface EmpMapper {
/**
* 查询总记录数
* @return
*/
//@Select("select count(*) from tlias.emp")
//public Long count();
/**
* 分页查询,获取列表数据
* @param start
* @param pageSize
* @return
*/
//@Select("select * from tlias.emp limit #{start},#{pageSize}")
//public List<Emp> page(Integer start, Integer pageSize);
/**
* 员工信息的查询
* @return
*/
//@Select("select * from tlias.emp")
public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
/**
* 批量删除
* @param ids
*/
void delete(List<Integer> ids);
/**
* 新增员工
* @param emp
*/
@Insert("insert into tlias.emp(tlias.emp.username, tlias.emp.name, tlias.emp.gender, tlias.emp.image, tlias.emp.job, tlias.emp.entrydate, tlias.emp.dept_id, tlias.emp.create_time, tlias.emp.update_time)" +
" values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entryDate}, #{deptId}, #{createTime}, #{updateTime})")
void save(Emp emp);
/**
* 根据id来查询员工
* @param id
* @return
*/
@Select("select * from tlias.emp where id = #{id}")
Emp getById(Integer id);
void update(Emp emp);
}
pojo
Dept
package com.itheima.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Dept {
private Integer id;
private String name;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
Emp
package com.itheima.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id;
private String username;
private String password;
private String name;
private Short gender;
private String image;
private Short job;
private LocalDate entryDate;
private Integer deptId;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
PageBean
package com.itheima.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.PrimitiveIterator;
/**
* 分页查询结果的封装类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageBean {
private Long total; //总记录数
private List rows; // 数据列表
}
Result
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
impl
DeptServiceImpl
package com.itheima.service.impl;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Override
public List<Dept> list() {
return deptMapper.list();
}
@Override
public void delete(Integer id) {
deptMapper.deleteById(id);
}
@Override
public void add(Dept dept) {
dept.setCreateTime(LocalDateTime.now());
dept.setUpdateTime(LocalDateTime.now());
deptMapper.insert(dept);
}
@Override
public Dept getById(Integer id) {
Dept dept = deptMapper.getById(id);
return dept;
}
@Override
public void update(Dept dept) {
dept.setUpdateTime(LocalDateTime.now());
deptMapper.update(dept);
}
}
EmpServiceImpl
package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;
/* @Override
public PageBean page(Integer page, Integer pageSize) {
// 1. 获取总记录数
Long conut = empMapper.count();
// 2. 获取分页查询结果列表
List<Emp> empList = empMapper.page((page - 1) * pageSize, pageSize);
// 3. 封装pageBean对象
PageBean pageBean = new PageBean(conut, empList);
return pageBean;
}*/
@Override
public PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
// 1. 设置分页参数
PageHelper.startPage(page, pageSize);
// 2. 执行查询
List<Emp> empList = empMapper.list(name, gender, begin, end);
Page<Emp> p = (Page<Emp>) empList;
// 3. 封装pageBean对象
PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
return pageBean;
}
@Override
public void delete(List<Integer> ids) {
empMapper.delete(ids);
}
@Override
public void save(Emp emp) {
emp.setCreateTime(LocalDateTime.now());
emp.setUpdateTime(LocalDateTime.now());
empMapper.save(emp);
}
@Override
public Emp getById(Integer id) {
return empMapper.getById(id);
}
@Override
public void update(Emp emp) {
emp.setUpdateTime(LocalDateTime.now());
empMapper.update(emp);
}
}
DeptService
package com.itheima.service;
import com.itheima.pojo.Dept;
import java.util.List;
public interface DeptService {
// 查询全部部门数据
List<Dept> list();
// 删除部门
void delete(Integer id);
//新增部门
void add(Dept dept);
// 查询部门
Dept getById(Integer id);
//修改部门
void update(Dept dept);
}
EmpService
package com.itheima.service;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import java.time.LocalDate;
import java.util.List;
public interface EmpService {
/**
* 分页查询
*
* @param page
* @param pageSize
* @return
*/
PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end);
/**
* 批量删除
* @param ids
*/
void delete(List<Integer> ids);
void save(Emp emp);
/**
* 根据id来查询员工
* @param id
* @return
*/
Emp getById(Integer id);
/**
* 更新员工
* @param emp
*/
void update(Emp emp);
}
EmpMapper.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.itheima.mapper.EmpMapper">
<update id="update">
update tlias.emp
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="gender != null">
gender = #{gender},
</if>
<if test="image != null and image != ''">
image = #{image},
</if>
<if test="job != null">
job = #{job},
</if>
<if test="entryDate != null">
entrydate = #{entryDate},
</if>
<if test="deptId != null">
dept_id = #{deptId},
</if>
<if test="updateTime != null">
update_time = #{updateTime}
</if>
</set>
where id = #{id}
</update>
<!--批量删除-->
<delete id="delete">
delete
from emp
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!--条件查询-->
<select id="list" resultType="com.itheima.pojo.Emp">
select *
from emp
<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>
</mapper>
文件上传
这里文件上传需要联网,因为我们是通过本地给阿里云OSS发送请求,具体操作是:
先获取文件的输入流,当同时上传文件名相同的文件时,为了避免文件被覆盖,我们可以通过修改上传的文件名,获得每个文件的UUID然后加上后缀名。
然后把文件上传到OSS,返回一个url,这个url就是我们图片的代理地址。
注意上传文件的类为MultipartFile
AliOSSUtils
package com.itheima.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
* 阿里云 OSS 工具类
*/
@Component
public class AliOSSUtils {
private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
private String accessKeyId = "LTAI5tLeUg5vpFijJjH8V2QW";
private String accessKeySecret = "PAePx18JDSm98sgTP4uruPfuclxAfS";
private String bucketName = "web-tlias-agoni";
/**
* 实现上传图片到OSS
*/
public String upload(MultipartFile file) throws IOException {
// 获取上传的文件的输入流
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的路径返回
}
}