自学内容网 自学内容网

SpringBoot

示例

创建一个 SpringBoot 项目整合 Mybatis-Plus

新建项目

项目信息

idea -> new project -> springboot,按照提示填写相应内容,点击下一步初始依赖

选择springboot项目所需要的基本依赖,如 Spring Web,JDBC API,Spring Data JPA 等点击下一步项目新建完成。

引入 mybatis-plus 依赖

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.4.3.4</version>
</dependency>

配置数据源,mybatis

新建 application.yaml 配置文件,配置以下基本信息

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/My_World?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:/dal/mapper/*.xml
  type-aliases-package: com.shore.my_spring_demo.dal.entity
  global-config:
    db-config:
      id-type: auto
  configuration:
    map-underscore-to-camel-case: true # 下划线转驼峰命名

数据库新建用户表

CREATE TABLE IF NOT EXISTS `user_info`
(
    `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
    `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
    `create_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建人',
    `update_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新人',
    `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '用户id',
    `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名称',
    `password` varchar(255) NOT NULL DEFAULT '' COMMENT '密码',
    `nick_name` varchar(255) NOT NULL DEFAULT '' COMMENT '昵称',
    `age` varchar(255) NOT NULL DEFAULT '' COMMENT '年龄',
    `email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱',
    `phone` varchar(255) NOT NULL DEFAULT '' COMMENT '电话',
    `address` varchar(255) NOT NULL DEFAULT '' COMMENT '地址',
    `auth` varchar(255) NOT NULL DEFAULT '' COMMENT '',
    INDEX idx_user_id(user_id),
    PRIMARY KEY(`id`)

) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4 COMMENT = '用户信息表';

创建实体类

类路径要与 yaml 文件中配置的路径一致

package com.shore.my_spring_demo.dal.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
@TableName("user_info")
public class UserEntity extends BaseEntity {
    private String userId;
    @TableField("user_name")
    private String username;
    private String password;
    @TableField("nick_name")
    private String nickname;
    private Integer age;
    private String email;
    private String phone;
    private String address;
    private String auth;
}

创建 Mapper 接口

Mapper 类应与 yaml 配置文件中的路径一致

package com.shore.my_spring_demo.dal.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shore.my_spring_demo.dal.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}

创建 Repository 接口及实现

package com.shore.my_spring_demo.dal.repo;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shore.my_spring_demo.web.domain.user.req.UserQueryPageReq;
import com.shore.my_spring_demo.dal.entity.UserEntity;

import java.util.List;

public interface UserServiceRepo {
    boolean addUser(UserEntity entity);

    UserEntity getUserById(Integer id);

    List<UserEntity> getUsersByConditions(UserQueryPageReq req);

    Page<UserEntity> getUsersByConditions(UserEntity userEntity, UserQueryPageReq req);
}

package com.shore.my_spring_demo.dal.repo.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shore.my_spring_demo.web.domain.user.req.UserQueryPageReq;
import com.shore.my_spring_demo.dal.entity.UserEntity;
import com.shore.my_spring_demo.dal.mapper.UserMapper;
import com.shore.my_spring_demo.dal.repo.UserServiceRepo;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceRepoImpl extends ServiceImpl<UserMapper, UserEntity> implements UserServiceRepo {

    @Override
    public boolean addUser(UserEntity entity) {
        return saveOrUpdate(entity);
    }

    @Override
    public UserEntity getUserById(Integer id) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return getOne(queryWrapper);
    }

    @Override
    public List<UserEntity> getUsersByConditions(UserQueryPageReq req) {
        return List.of();
    }

    @Override
    public Page<UserEntity> getUsersByConditions(UserEntity userEntity, UserQueryPageReq req) {
        return null;
    }
}

创建业务类及实现

package com.shore.my_spring_demo.service.user;

import com.shore.my_spring_demo.web.domain.user.req.UserAddReq;

public interface UserService {
    boolean register(UserAddReq userAddReq);
}
package com.shore.my_spring_demo.service.user.impl;

import com.shore.my_spring_demo.web.domain.user.req.UserAddReq;
import com.shore.my_spring_demo.dal.entity.UserEntity;
import com.shore.my_spring_demo.dal.repo.UserServiceRepo;
import com.shore.my_spring_demo.service.user.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserServiceRepo userServiceRepo;

    @Override
    public boolean register(UserAddReq userAddReq) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(userAddReq.getUsername());
        userEntity.setPassword(userAddReq.getPassword());
        userEntity.setEmail(userAddReq.getEmail());
        userEntity.setPhone(userAddReq.getPhone());
        userEntity.setNickname(userAddReq.getNickname());
        return userServiceRepo.addUser(userEntity);
    }
}

创建控制器

package com.shore.my_spring_demo.web.controller;

import com.shore.my_spring_demo.service.user.UserService;
import com.shore.my_spring_demo.web.domain.user.req.UserAddReq;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/shore/demo/user/register")
    public void register(@RequestBody UserAddReq req) {
        System.out.println(req.toString());
        userService.register(req);
    }
}

postman 访问

curl --location 'http://localhost:8080//shore/demo/user/register' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username":"admin001",
    "nickname":"001",
    "password":"4313",
    "age":11,
    "email":"shipeng_w@163.com",
    "phone":"110",
    "address":"China"
}'

整体目录结构

验证

查看数据库可以发现已经多了一条记录


原文地址:https://blog.csdn.net/qq_35201802/article/details/143651646

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!