“依”本日记(三)后端-数据库设计和实现注册功能

一、数据库设计

删除掉原型的user表

DROP TABLE user;

 新建数据库

添加需要的列,设置好主键,主要有以下几种 

-- auto-generated definition
create table user
(
    id           bigint auto_increment comment 'id',
    username     varchar(256)                        null comment '用户昵称',
    userAccount  varchar(256)                        null comment '账号',
    avatarUrl    varchar(1024)                       null comment '用户头像',
    gender       tinyint                             null comment '性别',
    userPassword varchar(512)                        not null comment '密码',
    phone        varchar(128)                        null comment '电话',
    email        varchar(512)                        null comment '邮箱',
    userStatus   int       default 0                 not null comment '用户状态',
    creamTime    timestamp default CURRENT_TIMESTAMP null comment '创建时间',
    updateTime   datetime  default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP null comment '更新时间',
    isDelete     tinyint   default 0                 not null comment '是否删除',
    primary key (id, userPassword)
)
    comment '用户表';

建表成功,输出结果:

二、后端-规整项目目录

新建controller文件夹,专门接受请求

新建service文件夹,编写业务逻辑

mapper文件夹是数据访问层,查询数据取数据,增删改查

model文件夹数据库对应的模型,封装类。

新建utils存放工具类,比如说加密,日期转换。

static主要放一下静态文件【删除】

templates放一些页面文件【删除】

三、后端-实现基本数据库操作

user对象和数据库的字段关联

一切从零开始,【删除】UserMapper类和SampleTest测试类

删代码,只保留最初的几行代码

安装MyBatisX工具包(代码生成器)

 数据库,对user表右键

使用MyBatisX插件生成对应文件

next,勾选部分选项

 将构建好的文件移到对应文件夹

生成的UserMapper.xml是与mapper文件夹里的UserMapper关联的

四、UserService创建一个测试类

鼠标放置文件名上,Alt键+Enter键,弹出

点击创建测试,直接确认,在test文件夹下生成了相同路径的test类

五、编写UserServiceTest

package com.yiping.usercenter.service;

import com.yiping.usercenter.model.domain.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

/**
 * 用户服务测试
 *
 */
@SpringBootTest
public class UserServiceTest {

    @Resource
    private UserService userService;

    @Test
    public void testAddUser(){
        User user = new User();
        userService.save();
    }
}

安装插件

对着user对象,Alt+Enter键,弹出选项框,选择Generate all setter with default value

赋予一些属性 

    public void testAddUser(){
        User user = new User();
        user.setUserPassword("hezihaifeng");
        user.setUsername("123");
        user.setUserAccount("https://profile-avatar.csdnimg.cn/5e8901935731460ebd08374edcdffa3b_weixin_62081337.jpg!1");
        user.setAvatarUrl("123");
        user.setGender(0);
        user.setPhone("123");
        user.setEmail("456");
        boolean result = userService.save(user);
        System.out.println(user.getId());
        Assertions.assertTrue(result);//断言:执行结果是否是你的预期结果
    }

【提示】ctrl+p键可以提示用什么方法

六、执行UserServiceTest

【Error1】Caused by: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: @TableId can't more than one in Class: "com.yiping.usercenter.model.domain.User". at com.baomidou.mybatisplus.core.toolkit.ExceptionUtils.mpe(ExceptionUtils.java:49)有一个关于 @TableId 注解使用不正确的问题。错误消息指出在 com.yiping.usercenter.model.domain.User 类中存在多个 @TableId 注解,而这是不允许的。@TableId 注解应该只在实体类的主键字段上使用一次。

找到包含TableId的地方将多余TableId注释(删除)

执行成功

七、后端-写登录逻辑 

引入依赖

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

在userServiceImpl里面写入用户服务的功能

package com.yiping.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiping.usercenter.model.domain.User;
import com.yiping.usercenter.service.UserService;
import com.yiping.usercenter.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户服务实现类
* @author Holiyar
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-03-28 22:53:45
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.校验
        if (StringUtils.isAnyBlank()) {
            return -1;
        }
        //2.校验账户
        if(userAccount.length()<4){
            return -1;
        }
        //3.校验密码
        if(userPassword.length()<8 || checkPassword.length() <8){
            return -1;
        }
        //4.账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if(count >0){
            return -1;
        }
        //5.账户不能包含特殊字符
        String validPattern  = "\\pP|\\PS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()){
            return  -1;
        }
        //6.密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            return -1;
        }
    }
}

在UserServiceTest写一个测试

@Test
    void testDigest()throws NoSuchAlgorithmException{
        MessageDigest md5 = MessageDigest.getInstance("MDS");
        String newPassword= DigestUtils.md5DigestAsHex(("abcd"+"mypassword").getBytes());
        System.out.println(newPassword);
    }

 【Error2】java.security.NoSuchAlgorithmException: MDS MessageDigest not available这个错误提示表明在 UserCenterApplicationTests 类的 testDigest() 方法中尝试使用了一个不可用的消息摘要算法。具体来说,错误是由于尝试使用 "MDS" 算法而引起的。然而,实际上应该是 "MD5" 算法。要解决这个问题,你需要将消息摘要算法的名称从 "MDS" 修改为 "MD5"。

@Test
void testDigest() throws NoSuchAlgorithmException {
    MessageDigest md5 = MessageDigest.getInstance("MD5"); // 修改这里的算法名称
    byte[] bytes = md5.digest("abcd".getBytes(StandardCharsets.UTF_8));
    String result = new String(bytes);
    System.out.println(result);
}
执行成功

八、后端-写接口逻辑

...
        //6.账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count >0){
            return -1;
        }

        //二、加密密码
        final String SALT ="hezhihaifeng";
        String encryptPassword =DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //三、.插入数据
        User user =new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if(!saveResult){
            return -1;
        }
        return  user.getId();
    }
}

 九、编写测试

    @Test
    void userRegister() {
        String userAccount ="hezihaifeng";
        String userPassword = "123";
        String checkPassword = "123";
        long result = userService.userRegister(userAccount,userPassword,checkPassword);
        Assertions.assertEquals(-1,result);
    }

执行成功


                
  • 27
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值