Back-end interface development - web front-end request interface to add, delete, modify and check the back-end database - example

1. The logic of back-end interface development is:

1.Application project starts
2. The front-end interface Url requests the back-end
3. The Controller gets the front-end request parameters and passes them to the intermediate component Service
4.Service calls Mapper.java
5. mapper.java is mapped to the mybatis statement in mapper.xml, which is similar to Sql statements operating the database< a i=5> 6. The project connects to the data table in the database through Mybatis 7. Add, delete, and modify data in the data table

This article is continued from the above:The central component Service calls Mapper to implement addition, deletion, modification and query

2. Use the Controller to receive and process the "Add Album" request

Createcontroller.AlbumController class under the root package of the project, add @RestController annotation to the class, and automatically assemble it in the classIAlbumService object, and the custom method handles the "Add Album" request:

@Slf4j
@RequestMapping("/album")
@RestController
public class AlbumController {
    
    

    /**
     * 不建议声明为具体的实现类,那样不利于代码“解耦”!
     */
    @Autowired
    private IAlbumService albumService;

    //直接网络请求添加
    //http://localhost:8080/album/add?name=TestAlbum001&description=TestDescription001&sort=88
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addNewAlbum(AlbumAddNewDTO albumAddNewDTO) {
    
    
        try {
    
    
            albumService.addNew(albumAddNewDTO);
            return "添加相册成功Ya!";
        } catch (CustomServiceException e) {
    
    
            String message = e.getMessage();
            log.error("addNewAlbum Exception {}", message);
            return message;
        }
    }
}

Start the project and you can test access throughhttp://localhost:8080/album/add?name=TestAlbum001&description=TestDescription001&sort=88. When the album data is successfully added, you can see the words 添加相册成功Ya! in the browser, as follows:
Insert image description here
Insert image description here

If the album name is occupied, you can see the custom exception 新增失败 reported as follows:

3. Interface call global code display

Continued from the previous article:2. The central component Service calls Mapper to implement addition, deletion, modification and query
Insert image description here

1. Define database addition, deletion, modification and query -mapper.java
package com.luoyang.small.mapper;


import com.luoyang.small.pojo.entity.Album;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author luoyang
 * @date 2023/11/28
 */
//标记当前类是数据访问组件类
@Repository
public interface AlbumMapper {
    
    

    /**
     * 插入相册数据
     *
     * @param album 相册数据
     * @return 受影响的行数
     */
    int insert(Album album);


    /**
     * 根据相册名称统计数据的数量
     *
     * @param name 相册名称
     * @return 匹配名称的相册数据的数量
     */
    int countByName(String name);


    /**
     * 根据相册名删除
     *
     * @param name 相册名称
     * @return 受影响的行数
     */
    int deleteByName(String name);

    /**
     * 根据相册名删除
     *
     * @param album 相册信息
     * @return 受影响的行数
     */
    int updateByName(Album album);

    /**
     * 根据相册名删除
     *
     * @return 受影响的行数
     */
    List<Album> selectAll();

}
2. Write Sql-like statements in xml -mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.luoyang.small.mapper.AlbumMapper">

    <!-- int insert(Album album); -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO pms_album (name, description, sort)
        VALUES (#{name}, #{description}, #{sort})
    </insert>

    <!-- int countByName(String name); -->
    <select id="countByName" resultType="int">
        SELECT count(*)
        FROM pms_album
        WHERE name = #{name}
    </select>


    <!-- int deleteByName(String name); -->
    <delete id="deleteByName">
        DELETE
        FROM pms_album
        WHERE name = #{name}
    </delete>


    <!-- int update(Album album); -->
    <update id="updateByName" parameterType="com.luoyang.small.pojo.entity.Album">
        UPDATE pms_album
        <set>
            <if test="name != null">
                name=#{name},
            </if>
            <if test="description != null">
                description=#{description},
            </if>
            <if test="sort != null">
                sort=#{sort},
            </if>
        </set>
        WHERE name=#{name}
    </update>


    <select id="selectAll" resultType="com.luoyang.small.pojo.entity.Album">
        SELECT id, name, description, sort
        FROM pms_album
    </select>

</mapper>
3. Define service addition, deletion, modification and check abstract methods
package com.luoyang.small.service;

import com.luoyang.small.pojo.dto.AlbumAddNewDTO;
import com.luoyang.small.pojo.entity.Album;

import java.util.List;

/**
 * 添加相册接口
 *
 * @author luoyang
 * @Date 2023/12/12
 */
public interface IAlbumService {
    
    
    void addNew(AlbumAddNewDTO albumAddNewDTO);

    void deleteAlbum(String name);

    void updateAlbum(AlbumAddNewDTO albumAddNewDTO);

    List<Album> selectAllAlbum();
}

4. Implement the abstract method of service addition, deletion, modification and query
package com.luoyang.small.service.impl;

import com.luoyang.small.ex.CustomServiceException;
import com.luoyang.small.mapper.AlbumMapper;
import com.luoyang.small.pojo.dto.AlbumAddNewDTO;
import com.luoyang.small.pojo.entity.Album;
import com.luoyang.small.service.IAlbumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 接口实现
 *
 * @author luoyang
 * @Date 2023/12/12
 */
@Slf4j
// 添加在类上,标记当前类是业务逻辑组件类,用法同@Component
@Service
public class IAlbumServiceImpl implements IAlbumService {
    
    
    /**
     * 添加在属性上,使得Spring自动装配此属性的值
     * 添加在构造方法上,使得Spring自动调用此构造方法
     * 添加在Setter方法上,使得Spring自动调用此方法
     */
    @Autowired
    private AlbumMapper albumMapper;

    @Override
    public void addNew(AlbumAddNewDTO albumAddNewDTO) {
    
    
        //检查相册名称是否占用
        String name = albumAddNewDTO.getName();
        int countByName = albumMapper.countByName(name);
        //如果数据已存在还继续插入,我们这边直接报异常,不添加。
        if (countByName > 0) {
    
    
            throw new CustomServiceException("相册名称已经被占用,新增失败");
        }

        //创建Album对象
        Album album = new Album();
        //复制属性到album
        BeanUtils.copyProperties(albumAddNewDTO, album);

        //执行插入数据
        int insert = albumMapper.insert(album);
        log.debug("插入结果 {}", insert);
    }

    @Override
    public void deleteAlbum(String name) {
    
    
        int delete = albumMapper.deleteByName(name);
        log.debug("删除结果 {}", delete);
    }

    @Override
    public void updateAlbum(AlbumAddNewDTO albumAddNewDTO) {
    
    
        //检查相册名称是否占用
        String name = albumAddNewDTO.getName();
        int countByName = albumMapper.countByName(name);
        //如果数据已存在还继续插入,我们这边直接报异常,不添加。
        if (countByName <= 0) {
    
    
            throw new CustomServiceException("该相册不存在");
        }

        //创建Album对象
        Album album = new Album();
        //复制属性到album
        BeanUtils.copyProperties(albumAddNewDTO, album);
        int update = albumMapper.updateByName(album);
        log.debug("更新结果 {}", update);
    }

    @Override
    public List<Album> selectAllAlbum() {
    
    
        List<Album> listAlbum = albumMapper.selectAll();
        log.debug("查询结果 {}", listAlbum.toString());
        return listAlbum;
    }
}

5. Test service addition, deletion, modification and calling method
package com.luoyang.small.service;

import com.luoyang.small.pojo.dto.AlbumAddNewDTO;
import com.luoyang.small.pojo.entity.Album;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author luoyang
 * @Date 2023/12/12
 */
@Slf4j
@SpringBootTest
public class AlbumServiceTests {
    
    
    //不建议声明为实现类型
    @Autowired
    IAlbumService iAlbumService;

    @Test
    void addNew() {
    
    
        AlbumAddNewDTO albumAddNewDTO = new AlbumAddNewDTO();
        albumAddNewDTO.setName("测试名称004");
        albumAddNewDTO.setDescription("测试简介004啦啦啦啦啦");
        albumAddNewDTO.setSort(100); // 注意:由于MySQL中表设计的限制,此值只能是[0,255]区间内的
        try {
    
    
            iAlbumService.addNew(albumAddNewDTO);
            log.debug("添加相册成功!");
        } catch (Exception e) {
    
    
            log.debug("添加相册失败,{}", e.getMessage());
        }
    }

    @Test
    void deleteAlbum() {
    
    
        try {
    
    
            String name = "测试名称001";
            iAlbumService.deleteAlbum(name);
            log.debug("{} 相册删除成功!", name);
        } catch (Exception e) {
    
    
            log.debug("删除相册失败,{}", e.getMessage());
        }
    }


    @Test
    void updateAlbum() {
    
    
        AlbumAddNewDTO albumAddNewDTO = new AlbumAddNewDTO();
        albumAddNewDTO.setName("测试名称004");
        albumAddNewDTO.setDescription("测试简介004更新哈哈哈");
        albumAddNewDTO.setSort(101); // 注意:由于MySQL中表设计的限制,此值只能是[0,255]区间内的
        try {
    
    
            iAlbumService.updateAlbum(albumAddNewDTO);
            log.debug("更新相册成功!");
        } catch (Exception e) {
    
    
            log.debug("更新相册失败,{}", e.getMessage());
        }
    }

    @Test
    void selectAll() {
    
    
        try {
    
    
            List<Album> albumList = iAlbumService.selectAllAlbum();
            log.debug("查询所有相册成功!{}", albumList.toString());
        } catch (Exception e) {
    
    
            log.debug("查询所有相册成功,{}", e.getMessage());
        }
    }

}

6. Web request calls Controller interface - formal call
package com.luoyang.small.controller;

import com.luoyang.small.ex.CustomServiceException;
import com.luoyang.small.pojo.dto.AlbumAddNewDTO;
import com.luoyang.small.pojo.entity.Album;
import com.luoyang.small.service.IAlbumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 相册web控制器
 *
 * @author luoyang
 * @Date 2023/12/13
 */
@Slf4j
@RequestMapping("/album")
@RestController
public class AlbumController {
    
    

    /**
     * 不建议声明为具体的实现类,那样不利于代码“解耦”!
     */
    @Autowired
    private IAlbumService albumService;

    //直接网络请求添加
    //http://localhost:8080/album/add?name=TestAlbum001&description=TestDescription001&sort=88
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addNewAlbum(AlbumAddNewDTO albumAddNewDTO) {
    
    
        try {
    
    
            albumService.addNew(albumAddNewDTO);
            return "添加相册成功Ya!";
        } catch (CustomServiceException e) {
    
    
            String message = e.getMessage();
            log.error("addNewAlbum Exception {}", message);
            return message;
        }
    }

    //直接网络请求删除
    //http://localhost:8080/album/delete?name=TestAlbum001&description=TestDescription001&sort=88
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deleteAlbum(AlbumAddNewDTO albumAddNewDTO) {
    
    
        if (albumAddNewDTO == null) {
    
    
            return "删除对象为空";
        }
        String name = albumAddNewDTO.getName();
        if (name == null || name.isEmpty()) {
    
    
            return "删除相册的名称为空";
        }
        try {
    
    
            albumService.deleteAlbum(name);
            return name + "相册,删除成功Ya!";
        } catch (Exception e) {
    
    
            String message = e.getMessage();
            log.error("deleteAlbum Exception {}", message);
            return message;
        }
    }

    //直接网络请求更新
    //http://localhost:8080/album/update?name=TestAlbum001&description=TestDescription001&sort=88
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String updateAlbum(AlbumAddNewDTO albumAddNewDTO) {
    
    
        if (albumAddNewDTO == null) {
    
    
            return "更新对象为空";
        }
        String name = albumAddNewDTO.getName();
        if (name == null || name.isEmpty()) {
    
    
            return "更新相册的名称为空";
        }
        try {
    
    
            albumService.updateAlbum(albumAddNewDTO);
            return name + "相册,更新成功Ya!";
        } catch (Exception e) {
    
    
            String message = e.getMessage();
            log.error("updateAlbum Exception {}", message);
            return message;
        }
    }

    //直接网络请求更新
    //http://localhost:8080/album/selectAll
    @RequestMapping(value = {
    
    "selectAll","fd"}, method = RequestMethod.GET)
    public List<Album> selectAllAlbum() {
    
    
        List<Album> albumList = null;
        try {
    
    
            albumList = albumService.selectAllAlbum();
//            return "查询全部成功Ya! 所有相册:"+albumList.toString();
        } catch (Exception e) {
    
    
            String message = e.getMessage();
            log.error("selectAllAlbum Exception {}", message);
//            return message;
        }
        return albumList;
    }

}
7. Interface calling effect-example

Query all:
Insert image description here
Create value, enjoy sharing!
Let’s get started with the backend 204146007

Guess you like

Origin blog.csdn.net/ly_xiamu/article/details/134995252