首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

剖析Java中的Entity、service、serviceImpl、Mapper以及Controller层之间的关系(代码诠释)

  • 25-03-03 21:21
  • 3845
  • 5403
blog.csdn.net

目录

  • 前言
  • 1. Demo1
  • 2. Demo2
  • 3. Demo3
  • 3. Mybatis自动生成

前言

学习了Java的相关方面知识之后,但对于各层次之间的关系以及部署,可能还会有些陌生感,下面以代码讲解各层之间的关系。
(企业中多数以Springboot为例,下面的代码都是以Springboot为例)
如果还停留在SSM基础或者补充Springboot的基础知识,也可在我的博客搜索。

1. Demo1

简单的Spring Boot项目的基本结构,其中包含了实体类、Mapper接口和XML文件、Service接口和实现类以及Controller。

根据实际需求进行适当的调整和扩展。在实际项目中,还需要配置数据库连接、事务管理等相关内容

一、定义实体类(Entity):

// User.java
public class User {
    private Long id;
    private String username;
    private String email;

    // Getters and setters
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

二、创建Mapper接口:

// UserMapper.java
import java.util.List;

public interface UserMapper {
    List<User> getAllUsers();
    User getUserById(Long id);
    void insertUser(User user);
    void updateUser(User user);
    void deleteUser(Long id);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

三、创建Mapper XML文件:(在resources目录下创建一个与Mapper接口同名的XML文件,定义SQL语句):


<mapper namespace="com.example.mapper.UserMapper">
    <select id="getAllUsers" resultType="com.example.model.User">
        SELECT * FROM users;
    select>

    <select id="getUserById" parameterType="Long" resultType="com.example.model.User">
        SELECT * FROM users WHERE id = #{id};
    select>

    <insert id="insertUser" parameterType="com.example.model.User">
        INSERT INTO users (username, email) VALUES (#{username}, #{email});
    insert>

    <update id="updateUser" parameterType="com.example.model.User">
        UPDATE users SET username = #{username}, email = #{email} WHERE id = #{id};
    update>

    <delete id="deleteUser" parameterType="Long">
        DELETE FROM users WHERE id = #{id};
    delete>
mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

四、创建Service接口和实现类:(实现类记得写@Service):

// UserService.java
public interface UserService {
    List<User> getAllUsers();
    User getUserById(Long id);
    void saveUser(User user);
    void updateUser(User user);
    void deleteUser(Long id);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
// UserServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void saveUser(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteUser(id);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

五、创建Controller:(用于处理HTTP请求):

// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public void saveUser(@RequestBody User user) {
        userService.saveUser(user);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

2. Demo2

上述改进方案可以摘Service中继承Iservice,使用继承类中的方法:

一、 修改UserService接口:在com.example.service包下创建一个UserService接口,继承IService:

// UserService.java
import com.example.model.User;
import com.baomidou.mybatisplus.extension.service.IService;

public interface UserService extends IService<User> {
    // 这里可以添加自定义的业务方法
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、创建UserServiceImpl实现类:(ServiceImpl已经实现了IService中的基本方法,在此基础上添加自定义的业务方法)

// UserServiceImpl.java
import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 这里可以添加自定义的业务方法的实现
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

三、使用UserService:在Controller中注入UserService,即可使用自动生成的方法

// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.example.model.User;
import com.example.service.UserService;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    @PostMapping
    public void saveUser(@RequestBody User user) {
        userService.save(user);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.removeById(id);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

3. Demo3

对于MybatisPlus中,其实更多的是Mapper来操作,上述Service的操作,最后都会通过Mapepr来操作

可以看这篇文章的示例讲解:快速理解Mybatis-plus中BaseMapper、IService和ServiceImpl

类似如下:

    @Test
    public void getUserById() {

        List<User> one = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getUsername,"manong"));
        System.out.println(one);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. Mybatis自动生成

使用Spring Boot和MyBatis的整合框架,可以借助MyBatis Generator自动生成实体类、Mapper接口以及XML文件。

以下是一个使用MyBatis Generator生成代码的简单示例:

一、pom.xml的依赖包:

<dependencies>
    

    
    <dependency>
        <groupId>org.mybatis.generatorgroupId>
        <artifactId>mybatis-generator-coreartifactId>
        <version>1.4.0version>
    dependency>
dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二、创建MyBatis Generator配置文件:在src/main/resources目录下创建一个generatorConfig.xml文件,用于配置生成器的参数:


DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="default" targetRuntime="MyBatis3">

        
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/your_database" userId="your_username" password="your_password"/>

        
        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>

        
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java"/>

        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        
        <table tableName="users" domainObjectName="User"/>

    context>
generatorConfiguration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

三、通过命令行或者IDE插件运行MyBatis Generator,生成代码:

mvn mybatis-generator:generate
  • 1
文章知识点与官方知识档案匹配,可进一步学习相关知识
Java技能树首页概览145194 人正在系统学习中
码农研究僧
微信公众号
1.框架等前沿技术 2.日常生活 3.技术交流
注:本文转载自blog.csdn.net的码农研究僧的文章"https://blog.csdn.net/weixin_47872288/article/details/135258686"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top