①添加依赖
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.2</version>
</dependency>
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>springboot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.6</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.example.springboot.SpringbootApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
②新建MybatisPlusConfig配置页
MybatisPlusConfig:分页插件
package com.example.springboot.common;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.springboot.mapper")
public class MybatisPlusConfig {
/**
* 添加分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//如果配置多个插件,切记分页最后添加
return interceptor;
}
}
③修改实体类User
User:
package com.example.springboot.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@TableName("user")
public class User {
@TableId(type= IdType.AUTO)
private Integer id;
private String username;
private String password;
private String name;
private String phone;
private String email;
private String address;
private String avatar;
private String role;
@TableField(exist = false)
private String token;
}
④修改UserMapper
UserMapper:
package com.example.springboot.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springboot.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user where id=#{id}")
User selectbyid(Integer id);
}
⑤修改UserService
UserService:
package com.example.springboot.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.TokenUtils;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
@Service
public class UserService extends ServiceImpl<UserMapper,User> {
@Resource
UserMapper userMapper;
@Override
public boolean save(User entity){
if(StrUtil.isBlank(entity.getName())){
entity.setName(entity.getUsername());
}
if(StrUtil.isBlank(entity.getPassword())){
entity.setPassword("123");
}
if(StrUtil.isBlank(entity.getRole())){
entity.setRole("用户");
}
return super.save(entity);
}
public User selectbyUsername(String username){
QueryWrapper<User> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("username",username);
return getOne(queryWrapper);
}
public User login(User user) {
User dbuser=selectbyUsername(user.getUsername());
if(dbuser == null){
throw new ServiceException("账号不存在");
}
if(!user.getPassword().equals(dbuser.getPassword())){
throw new ServiceException("账号或者密码错误");
}
String token=TokenUtils.createToken(dbuser.getId().toString(),dbuser.getPassword());
dbuser.setToken(token);
return dbuser;
}
public User register(User user) {
User dbuser=selectbyUsername(user.getUsername());
if(dbuser != null){
throw new ServiceException("用户名已存在");
}
userMapper.insert(user);
return user;
}
public void resetPassword(User user) {
User dbuser=selectbyUsername(user.getUsername());
if(dbuser==null){
throw new ServiceException("用户不存在");
}
if(!user.getPhone().equals(dbuser.getPhone())){
throw new ServiceException("验证错误");
}
dbuser.setPassword("123");
updateById(dbuser);
}
}
⑥修改UserController:
UserConrtoller:
package com.example.springboot.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userservice;
@PostMapping("/add")
public Result add(@RequestBody User user){
try{
userservice.save(user);
}catch(Exception e){
if(e instanceof DuplicateKeyException){
return Result.error("插入数据错误");
}else{
return Result.error("系统错误");
}
}
return Result.success();
}
@PutMapping("/update")
public Result update(@RequestBody User user){
userservice.updateById(user);
return Result.success();
}
@DeleteMapping("/delete/{id}")
public Result delete(@PathVariable Integer id){
User currentUser= TokenUtils.getCurrentUser();
if(id.equals(currentUser.getId())){
throw new ServiceException("不能删除当前用户");
}
userservice.removeById(id);
return Result.success();
}
@DeleteMapping("/delete/batch")
public Result batchDelete(@RequestBody List<Integer> ids){
User currentUser=TokenUtils.getCurrentUser();
if(currentUser != null&¤tUser.getId()!=null &&ids.contains(currentUser.getId())){
throw new ServiceException("不能删除当前用户");
}
userservice.removeBatchByIds(ids);
return Result.success();
}
@GetMapping("/selectall")
public Result selectall(){
List<User>userlist=userservice.list(new QueryWrapper<User>().orderByDesc("id"));
return Result.success(userlist);
}
@GetMapping("/selectbyid/{id}")
public Result selectbyid(@PathVariable Integer id){
User user=userservice.getById(id);
return Result.success(user);
}
@GetMapping("/selectByPage")
public Result selectByPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam String username,
@RequestParam String name){
QueryWrapper<User>queryWrapper=new QueryWrapper<User>().orderByDesc("id");
queryWrapper.like(StrUtil.isNotBlank(username),"username",username);
queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
Page<User>page=userservice.page(new Page<>(pageNum,pageSize),queryWrapper);
return Result.success(page);
}
}
⑦修改前端User页
User:
<template>
<div>
<div>
<el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
<el-input style="width: 200px;margin: 0 10px" placeholder="查询姓名" v-model="name"></el-input>
<el-button type="primary" @click="load(1)">查询</el-button>
<el-button type="info" @click="reset">重置</el-button>
</div>
<div style="margin: 10px 0">
<el-button type="primary" @click="handleAdd">新增</el-button>
<el-button type="danger" @click="delbatch">批量删除</el-button>
</div>
<el-table @selection-change="handleSelectionChange" :data="tableData" stripe :header-cell-style="{backgroundColor:'aliceblue',color:'#666'} ">
<el-table-column type="selection" width="55" align="center">
</el-table-column>
<el-table-column prop="id" label="ID" width="70"></el-table-column>
<el-table-column prop="username" label="用户名"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="phone" label="手机号"></el-table-column>
<el-table-column prop="email" label="邮箱"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column label="头像">
<template v-slot="scope">
<div style="display: flex;align-items: center">
<el-image style="width: 50px;height: 50px;border-radius: 50%" v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
</div>
</template>
</el-table-column>
<el-table-column prop="role" label="角色"></el-table-column>
<el-table-column label="操作" align="center" width="180">
<template v-slot="scope">
<div style="display: flex">
<el-button type="primary" plain size="mini" @click="handleEdit(scope.row)">编辑</el-button>
<el-button type="danger" plain size="mini" @click="del(scope.row.id)">删除</el-button>
</div>
</template>
</el-table-column>
</el-table>
<div class="block" style="margin: 10px 0">
<span class="demonstration">完整功能</span>
<el-pagination
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[100, 200, 300, 400]"
:page-size="pageSize"
layout="total, prev, pager, next"
:total="total">
</el-pagination>
</div>
<el-dialog title="收货地址" :visible.sync="formVisible" width="30%">
<el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" ></el-input>
</el-form-item>
<el-form-item label="姓名" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="电话" prop="phone">
<el-input v-model="form.phone"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="form.email"></el-input>
</el-form-item>
<el-form-item label="地址" prop="address">
<el-input type="textarea" v-model="form.address"></el-input>
</el-form-item>
<el-form-item label="角色" prop="role">
<el-radio-group v-model="form.role">
<el-radio label="管理员"></el-radio>
<el-radio label="用户"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="头像">
<el-upload
class="avatar-uploader"
action="http://localhost:9090/file/upload"
:headers="{ token: user.token }"
:file-list="form.avatar?[form.avatar]:[]"
list-type="picture"
:on-success="handleAvatarSuccess">
<el-button type="primary">上传头像</el-button>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name:'User',
data(){
return{
tableData:[],
pageNum:1,
pageSize:5,
username:'',
name:'',
total:0,
formVisible:false,
form:{},
user:JSON.parse(localStorage.getItem('honey-user'||'{}')),
rules:{
username:[{
required:true,
message:'请输入用户名',
trigger:'blur'
}]
},
ids:[]
}
},
created() {
this.load()
},
methods:{
delbatch(){
if(!this.ids.length){
this.$message.warning("请选择数据")
return
}
this.$confirm('您确认删除吗','确认删除',{type:'warning'}).then(response=>{
this.$request.delete('/user/delete/batch',{data:this.ids}).then(res=>{
if(res.code === '200'){
this.$message.success('操作成功')
this.load(1)
}else{
this.$message.error(res.msg)
}
})
}).catch(()=>{})
},
handleSelectionChange(rows){
this.ids=rows.map(v=>v.id)
},
del(id){
this.$confirm('您确认删除吗','确认删除',{type:'warning'}).then(response=>{
this.$request.delete('/user/delete/'+id).then(res=>{
if(res.code === '200'){
this.$message.success('操作成功')
this.load(1)
}else{
this.$message.error(res.msg)
}
})
}).catch(()=>{})
},
handleEdit(row){
this.form=JSON.parse(JSON.stringify(row))
this.formVisible=true
},
handleAdd(){
this.form={role:'用户'}
this.formVisible=true
},
save(){
this.$refs.formRef.validate((valid)=>{
if(valid){
this.$request({
url:this.form.id? '/user/update' : '/user/add',
method:this.form.id? 'PUT' : 'POST',
data:this.form
}).then(res=>{
if(res.code === '200'){
this.$message.success('保存成功')
this.load(1)
this.formVisible=false
}else{
this.$message.error(res.msg)
}
})
}
})
},
handleAvatarSuccess(response,file,fileList){
console.log(response)
this.form.avatar=response.data
},
reset(){
this.name=''
this.username=''
this.load()
},
load(pageNum){
if(pageNum){
this.pageNum=pageNum
}
this.$request.get('/user/selectByPage',{
params:{
pageNum:this.pageNum,
pageSize:this.pageSize,
username:this.username,
name:this.name
}
}).then(res=>{
this.tableData=res.data.records
this.total=res.data.total
})
},
handleCurrentChange(pageNum){
this.load(pageNum)
},
}
}
</script>
<style scoped>
</style>