首页 > 编程语言 >Java Spring Boot Controller、Service、DAO实践

Java Spring Boot Controller、Service、DAO实践

时间:2024-01-10 14:13:09浏览次数:27  
标签:Java Service Spring id return UserInfo import com public

如果你用过 Spring MVC,那就对 Controller、Service、DAO 三者的概念一定不陌生,我们通过 Controller 来接收请求和返回响应,具体的业务处理则放在 Service层 处理,而 DAO 则实现具体与数据库等持久层的操作。

今天从分层的角度来学习下在 Spring Boot 中的简单应用,业务场景也很简单,就是实现 用户信息 的增删改查,本文重在 这三者 的应用,涉及到更好设计的功能这里不讨论。

本人水平有限,主要针对新手学习用,如有不足,请大佬忽略或轻喷。

依赖

新建个 Spring Boot 项目,添加下面的依赖:

<!--  mysql driver      -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>
<!-- mp依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.5</version>
</dependency>
<!--   @Data     -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>
<!--  params validate -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

主要目录

目录结构如下图所示:

image.png

配置文件

application.yml内容:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://{ip}:3306/mybatis_demo?&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true

后面的实现从 DAO -> Service -> Controller 依次实现。

DAO(Mapper)

新建个 UserInfoMapper.java

package com.example.springbootmybatisplusdemo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplusdemo.entity.UserInfo;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}

Service

实现简单的功能:

package com.example.springbootmybatisplusdemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootmybatisplusdemo.entity.UserInfo;
import com.example.springbootmybatisplusdemo.mapper.UserInfoMapper;
import com.example.springbootmybatisplusdemo.utils.CryptoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserInfoServiceImpl implements UserInfoService<UserInfo> {

    @Autowired
    private UserInfoMapper userInfoMapper;

    private static final String salt = "crypto";

    public UserInfoServiceImpl() {
        super();
    }

    @Override
    public boolean createUserInfo(UserInfo userInfo) {
        // check if exist repeated user
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("phone", userInfo.getPhone());
        Long count = userInfoMapper.selectCount(qw);
        if (count > 0) return false;

        // crypto password
        String pwd = userInfo.getPassword() + salt;
        userInfo.setPassword(CryptoUtils.md5Sum(pwd));

        // insert into database
        int affected = userInfoMapper.insert(userInfo);
        if (affected != 1) return false;

        return true;
    }

    @Override
    public boolean deleteUserInfo(Long id) {
        // logic delete
        int affected = userInfoMapper.deleteById(id);
        if (affected != 1) return false;

        return true;
    }

    @Override
    public UserInfo getUserInfo(Long id) {
        // query user info by userId
        UserInfo user = userInfoMapper.selectById(id);
        return user;
    }

    @Override
    public boolean updateUserInfo(UserInfo userInfo) {
        // update table set ...
        int affected = userInfoMapper.updateById(userInfo);
        if (affected != 1) return false;

        return true;
    }
}

Controller

实现几个接口:

package com.example.springbootmybatisplusdemo.controller;

import com.example.springbootmybatisplusdemo.entity.UserInfo;
import com.example.springbootmybatisplusdemo.service.UserInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserManagerController {

    @Autowired
    UserInfoServiceImpl userInfoService;

    @PostMapping("/register")
    public Object register(@RequestBody UserInfo userInfo) {
        boolean result = userInfoService.createUserInfo(userInfo);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result);
        return data;
    }

    @DeleteMapping("/deregister/{id}")
    public Object deregister(@PathVariable("id") Long id) {
        boolean result = userInfoService.deleteUserInfo(id);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result);
        return data;
    }

    @GetMapping("/info/{id}")
    public UserInfo getInfo(@PathVariable("id") Long id) {
        UserInfo user = userInfoService.getUserInfo(id);
        return user;
    }

    @PostMapping("/update/")
    public Object updateInfo(@RequestBody UserInfo userInfo) {
        userInfoService.updateUserInfo(userInfo);
        return null;
    }
}

最后在 启动入口处 加上注解:

package com.example.springbootmybatisplusdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.example.springbootmybatisplusdemo.mapper")
public class SpringbootMybatisPlusDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisPlusDemoApplication.class, args);
    }

}

p.s. UserInfo用户bean

package com.example.springbootmybatisplusdemo.entity;

import com.baomidou.mybatisplus.annotation.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@TableName(value = "user_info")
public class UserInfo {
    @TableId(type = IdType.AUTO)
    private Long id;

    @NotBlank
    @NotNull
    @Size(min = 4, max = 30, message = "name's length is too long or to short.")
    private String name;

    @Size(min = 8, max = 20)
    private String password;

    private String address;

    @Size(min = 11, max = 11, message = "phone's length should be 11.")
    private String phone;

    @TableField(fill = FieldFill.INSERT, value = "created_time")
    private LocalDateTime createdTime;

    @TableField(fill = FieldFill.UPDATE, value = "updated_time")
    private LocalDateTime updatedTime;

    @TableLogic(value = "false", delval = "true")
    @TableField(value = "is_deleted")
    private boolean isDeleted;
}

工具类:

package com.example.springbootmybatisplusdemo.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CryptoUtils {
    public static final String ALGO = "MD5";

    public static String md5Sum(String val) {
        if (val == null) val = "";

        String str = "";
        try {
            MessageDigest msgD = MessageDigest.getInstance(ALGO);
            msgD.update(val.getBytes());
            byte[] bytes = msgD.digest();

            int i;
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < bytes.length; j++) {
                i = bytes[j];
                if (i < 0) i += 256;
                if (i < 16) builder.append("0");

                builder.append(Integer.toHexString(i));
            }

            str = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return str;
    }

    public static void main(String[] args) {
        System.out.println(CryptoUtils.md5Sum("Hello world!" + "crypto"));
    }
}

创建表的 SQL 语句:

CREATE TABLE `user_info` (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    password CHAR(32) NOT NULL,
    address varchar(50) DEFAULT '',
    phone CHAR(11) NOT NULL UNIQUE KEY,
    created_time DATETIME NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
    updated_time DATETIME NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '修改时间',
    is_deleted BOOLEAN
) ENGINE =innodb, CHARSET =utf8;

标签:Java,Service,Spring,id,return,UserInfo,import,com,public
From: https://www.cnblogs.com/davis12/p/17956349

相关文章

  • Spring Cloud Hystrix
    在SpringCloud中使用了Hystrix来实现断路器的功能。Hystrix是Netflix开源的微服务框架套件之一,该框架目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以......
  • SpringBoot WebSocket 样例
    SpringBootWebSocket样例pom.xml依赖配置<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>javax.webso......
  • jasypt-spring-boot 配置文件加密样例
    jasypt-spring-boot配置文件加密样例首先引入pom.xml<!--低版本的jdk(如1.8.0_25-b18)中会出现Failedtobindpropertiesunder'xxx'tojava.lang.String,不会在高版本的jdk(如1.8.0_161)运行环境中出现;原因:加密引发异常。原因是您正在使用强加密算法,并且您尚未在此Java......
  • 对比Spring Boot中的JdbcClient与JdbcTemplate
    本文我们一起看看SpringBoot中JdbcClient和JdbcTemplate之间的差异。以下内容使用的Java和SpringBoot版本为:Java21SpringBoot3.2.1假设我们有一个ICustomerService接口:publicinterfaceICustomerService{List<Customer>getAllCustomer();Optio......
  • 多线程任务管理:深入学习CompletionService的应用
    第1章:引言大家好,我是小黑,咱们都知道,在现代软件开发中,特别是对于Java程序员来说,高效地处理并发任务是一个非常关键的技能。就像在繁忙的餐厅里,多个厨师同时烹饪不同的菜肴一样,程序中的多线程也需要协调地工作。在这个背景下,Java的CompletionService就像是一个管理厨师的调度员,它......
  • java深copy
    使用工具类SerializationUtils说明:由于org.apache.commons.lang3包提供,AlarmDescDetailsDtor=SerializationUtils.clone(request);r.setAlarmObjectType(AlarmObjectType.APPLICATION);测试验证AlarmDescDetailsDtorequest1=newAlarmDescDetailsDto();request1.......
  • 8、SpringBoot2之打包及运行
    为了演示高级启动时动态配置参数的使用,本文在SpringBoot2之配置文件的基础上进行8.1、概述普通的web项目,会被打成一个war包,然后再将war包放到tomcat的webapps目录中;当tomcat启动时,在webapps目录中的war包会自动解压,此时便可访问该web项目的资源或服务;因为......
  • C# 调用WebService 笔记
    最近开发工作涉及到一些关于webService调用的问题,因为太久没有做过这部分,踩了一点坑,做个笔记记录一下,避免下次踩坑。说明C#调用webService基本有两种方法,一种是静态调用,也就是添加到服务引用,还有一种方式是动态引用,动态引用的主要思路是通过url将DLL下载到本地,然后进行调用,这里......
  • 基于java的小型超市管理系统
    使用旧方法对超市信息进行系统化管理已经不再让人们信赖了,把现在的网络信息技术运用在超市信息的管理上面可以解决许多信息管理上面的难题,比如处理数据时间很长,数据存在错误不能及时纠正等问题。这次开发的小型超市管理系统有管理员,用户,员工。管理员功能有个人中心,用户管理,员工管......
  • 基于Java框架失物招领信息交互平台
    本论题国内外研究动态及研究意义:在我们的生活中,丢东西这件事经常发生,处处可见,丢钥匙、丢钱包、丢手机、丢宠物等等。一旦丢东西,就会给失主带来极大不便和损失。所以,在我们生活工作的社区里,就需要失物招领系统,给失主和捡到物品的人提供一个平台,让失主尽快找回失物,减少损失。失主可......