后端接口开发-web前台请求接口对后台数据库增删改查-实例

一、后端接口开发的逻辑是:

1.Application项目启动
2.前台接口Url请求后台
3.Controller控制拿到前台请求参数,传递给中间组件Service
4.Service调用Mapper.java
5. mapper.java映射到mapper.xml中的mybatis语句,类似Sql语句操作数据库
6.其中项目通过Mybatis连接数据库中的数据表
7.数据表数据增删改查

本文接上文:中枢组件Service调用Mapper实现增删改查

二、使用Controller控制器接收并处理“添加相册”的请求

在项目的根包下创建controller.AlbumController类,在类上添加@RestController注解,在类中自动装配IAlbumService的对象,并且,自定义方法处理“添加相册”的请求:

@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/add?name=TestAlbum001&description=TestDescription001&sort=88测试访问,当成功添加相册数据时,在浏览器中可以看到添加相册成功Ya!的字样,如下:
在这里插入图片描述
在这里插入图片描述

如果相册名称被占用,可以看到报错的自定义异常 新增失败 的字样,如下:

三、接口调用全局代码展示

接前文:2.中枢组件Service调用Mapper实现增删改查
在这里插入图片描述

1.定义数据库增删改查 -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.xml编写类似Sql语句 -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.定义service增删改查抽象方法
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.实现service增删改查抽象方法
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.测试service增删改查调用方法
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请求调用Controller接口-正式调用
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.接口调用效果-举例

查询全部:
在这里插入图片描述
创造价值,乐哉分享!
一起入门后端 204146007

猜你喜欢

转载自blog.csdn.net/ly_xiamu/article/details/134995252