Analyze the relationship between Entity, service, serviceImpl, Mapper and Controller layers in Java (code interpretation)

Preface

After learning the relevant knowledge of Java, you may still feel a little unfamiliar with the relationship and deployment of each layer. The following uses code to explain the relationship between each layer.
(Most companies use Springboot as an example. The following codes use Springboot as an example.)
If you are still stuck on the basics of SSM or supplement the basic knowledge of Springboot, you can also search on my blog.

1. Demo1

The basic structure of a simple Spring Boot project, which includes entity classes, Mapper interfaces and XML files, Service interfaces and implementation classes, and Controllers.

Make appropriate adjustments and expansions based on actual needs. In actual projects, it is also necessary to configure database connections, transaction management and other related content.

1. Define the entity class (Entity):

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

    // Getters and setters
}

2. Create Mapper interface:

// 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);
}

3. Create Mapper XML file: (Create an XML file with the same name as the Mapper interface in the resources directory and define the SQL statement):

<!-- UserMapper.xml -->
<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>

4. Create the Service interface and implementation class: (Remember to write @Service for the implementation class):

// UserService.java
public interface UserService {
    
    
    List<User> getAllUsers();
    User getUserById(Long id);
    void saveUser(User user);
    void updateUser(User user);
    void deleteUser(Long id);
}
// 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);
    }
}

5. Create Controller: (used to handle HTTP requests) :

// 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);
    }
}

2.Demo2

The above improvement plan can inherit Iservice from Service and use the methods in the inherited class:

1. Modify the UserService interface: Create a UserService interface under the com.example.service package and inherit IService:

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

public interface UserService extends IService<User> {
    
    
    // 这里可以添加自定义的业务方法
}

2. Create the UserServiceImpl implementation class: (ServiceImpl has already implemented the basic methods in IService, and adds custom business methods on this basis)

// 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 {
    
    
    // 这里可以添加自定义的业务方法的实现
}

3. Use UserService: Inject UserService in Controller to use the automatically generated method

// 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);
    }
}

3. Demo3

For MybatisPlus, it is actually more operated by Mapper. The above-mentioned Service operations will eventually be operated by Mapepr.

You can see the example explanation in this article: Quickly understand BaseMapper, IService and ServiceImpl in Mybatis-plus

Something like this:

    @Test
    public void getUserById() {
    
    

        List<User> one = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getUsername,"manong"));
        System.out.println(one);
    }

3. Mybatis automatically generates

Using the integrated framework of Spring Boot and MyBatis, you can use MyBatis Generator to automatically generate entity classes, Mapper interfaces and XML files.

Here is a simple example using MyBatis Generator to generate code:

1. Dependency packages of pom.xml:

<dependencies>
    <!-- 其他依赖 -->

    <!-- MyBatis Generator 依赖 -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>

2. Create the MyBatis Generator configuration file: Create a generatorConfig.xml file in the src/main/resources directory to configure the parameters of the generator:

<!-- 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"/>

        <!-- Mapper接口生成位置 -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <!-- XML文件生成位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <!-- 表配置 -->
        <table tableName="users" domainObjectName="User"/>

    </context>
</generatorConfiguration>

3. Run MyBatis Generator through the command line or IDE plug-in to generate code:

mvn mybatis-generator:generate

Guess you like

Origin blog.csdn.net/weixin_47872288/article/details/135258686