Spring Boot项目中的Controller、Service、Mapper和Entity层间的关系及作用

目录

一、Spring Boot项目中的层级结构

二、各层详解

(一)Controller层(控制层)

(二)Service层(业务逻辑层)

(三)Mapper层(数据访问层)

(四)Entity层(实体层)


一、Spring Boot项目中的层级结构

一个完整的Spring Boot项目主要包括Controller层、Service层、Mapper层和Entity层组成。

二、各层详解

(一)Controller层(控制层)

Controller层主要负责接收前端请求并返回响应,它是应用程序的入口点。在Spring Boot中,Controller层通常使用@RestController@Controller注解来标识。Controller层的主要作用是接收客户端请求,将请求参数传递给Service层进行处理,并将处理结果以适当的形式返回给客户端。

UserController类

package com.itxinian.controller;

import com.itxinian.entity.Result;
import com.itxinian.entity.User;
import com.itxinian.service.UserService;
import com.itxinian.utils.JwtUtil;
import com.itxinian.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
        User u = userService.findByUserName(username);
        if(u == null){
            userService.register(username,password);
            return Result.success();
        }else{
            return Result.error("用户名已被使用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")String password){
        User loginUser = userService.findByUserName(username);

        if(loginUser == null){
            return Result.error("用户名错误");
        }


        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}

(二)Service层(业务逻辑层)

Service层通常位于Controller层和数据访问层之间,负责处理应用程序的业务逻辑。Service层负责执行业务规则、数据验证、数据处理等操作。它接收来自Controller层的请求,调用Mapper层的方法进行数据操作,并将结果返回给Controller层。Service层的设计使得业务逻辑与数据访问逻辑分离,提高了代码的可维护性和可重用性。

UserService接口,主要用于定义接口(业务逻辑)

package com.itxinian.service;

import com.itxinian.entity.User;

public interface UserService {
    User findByUserName(String username);

    void register(String username, String password);
}

UserServiceImpl类,主要用于实现UserService接口

package com.itxinian.service.impl;

import com.itxinian.mapper.UserMapper;
import com.itxinian.entity.User;
import com.itxinian.service.UserService;
import com.itxinian.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Userserviceimpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        String md5String = Md5Util.getMD5String(password);

        userMapper.add(username,md5String);
    }
}

(三)Mapper层(数据访问层)

Mapper层也称为Dao层或Repository层,它是数据持久层的组件。Mapper层的主要作用是访问数据库,执行数据的增删改查操作。它通常包含一些基本的SQL语句或使用ORM框架提供的API来执行数据库操作。Mapper层的设计使得数据访问逻辑与业务逻辑分离,提高了代码的可维护性和可重用性。

UserMapper接口

package com.itxinian.mapper;

import com.itxinian.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("select * from user where username=#{username}")
    User findByUserName(String username);
    @Insert("insert into user(username,password,create_time,update_time)" +
            " values(#{username},#{password},now(),now())")
    void add(String username, String password);
}

(四)Entity层(实体层)

Entity层是存放实体的类,类中定义了多个属性,并且与数据库表的字段保持一致。Entity层的定义主要用于定义与数据库对象对应的属性,提供get/set方法、toString方法以及有参无参构造函数等。一个数据库表通常对应了一个Entity类,使得开发人员可以更加方便地操作数据库表中的数据。

User类

package com.itxinian.entity;



import lombok.Data;

import java.time.LocalDateTime;

@Data
public class User {
    private Integer id;//主键ID
    private String username;//用户名
    private String password;//密码
    private String nickname;//昵称
    private String email;//邮箱
    private String userPic;//用户头像地址
    private LocalDateTime createTime;//创建时间
    private LocalDateTime updateTime;//更新时间
}

  • 24
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 项目,通常会采用 MVC 架构的设计思路,将代码按照功能分为 MapperEntityServiceController 四个次。 1. Mapper Mapper 是连接数据库和业务逻辑的桥梁,它使用 MyBatis 等 ORM 工具来实现数据库操作。在 Mapper ,通常会定义以下内容: - 定义 SQL 语句和参数映射 - 定义查询条件和排序方式 - 定义对数据库的增删改查操作 Mapper 的示例代码如下: ``` @Mapper public interface UserMapper { @Select("select * from user where id=#{id}") User getUserById(Long id); @Insert("insert into user(name, age) values(#{name}, #{age})") int addUser(User user); @Update("update user set name=#{name}, age=#{age} where id=#{id}") int updateUser(User user); @Delete("delete from user where id=#{id}") int deleteUser(Long id); } ``` 2. Entity Entity 是与数据库表进行映射的实体类。在 Entity ,通常会定义以下内容: - 定义实体类的属性和对应的数据库表字段 - 定义实体类之间的关系 Entity 的示例代码如下: ``` @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 3. Service Service 是业务逻辑的处理,它主要负责处理业务逻辑和调用 Mapper 完成数据库操作。在 Service ,通常会定义以下内容: - 定义业务逻辑的方法 - 定义事务的管理方法 Service 的示例代码如下: ``` @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.getUserById(id); } public int addUser(User user) { return userMapper.addUser(user); } public int updateUser(User user) { return userMapper.updateUser(user); } public int deleteUser(Long id) { return userMapper.deleteUser(id); } } ``` 4. ServiceImpl ServiceImpl Service 的实现类,它实现了 Service 定义的业务逻辑方法,并调用 Mapper 完成数据库操作。在 ServiceImpl ,通常会定义以下内容: - 实现 Service 定义的业务逻辑方法 - 定义事务的管理方法 ServiceImpl 的示例代码如下: ``` @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.getUserById(id); } @Override public int addUser(User user) { return userMapper.addUser(user); } @Override public int updateUser(User user) { return userMapper.updateUser(user); } @Override public int deleteUser(Long id) { return userMapper.deleteUser(id); } } ``` 以上就是 Spring Boot MapperEntityServiceServiceImpl 四个次的概述和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值