ReceiveAddressJsonController.java



package com.example.controller;


import com.example.entity.ReceiveAddress;
import com.example.service.IReceiveAddressService;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */

@RestController  //@Controller + @ResponseBody 所有方法都返回json数据
@RequestMapping("/receive-addressJSon")
public class ReceiveAddressJsonController {
    @Autowired
    private IReceiveAddressService addressService;


    /**
     * 根据主键查询
     * @param arrId
     * @return
     */
    @GetMapping("{addrId}") //URL:http://localhost:8080/app/receive-addressJSon/103
    public ServerResult getById(@PathVariable("addrId") Integer arrId){//URL :  http://localhost:8080/app/receive-addressJSon/103

        return addressService.getById(arrId);
    }

    /**
     * 查询所有     //URL :  http://localhost:8080/app/receive-addressJSon/
     * @return
     */
    @GetMapping("")
    public ServerResult getAll(){
        int custId = 1;// 模拟的登录用户id
        return addressService.getAll(custId);
    }





    //@GetMapping("page/{pageNum}")
    //public List<ReceiveAddress> getByPage(@PathVariable("pageNum") Integer pageNum){
    //    return null;
    //}


    /**
     * 新增收件地址
     * @param receiveAddress
     * @return
     */
    @PostMapping
    public ServerResult save(ReceiveAddress receiveAddress){
        int customerId = 1;
        receiveAddress.setCustId(customerId);
        receiveAddress.setStatus(1);
        receiveAddress.setVersion(1);
        receiveAddress.setCreateTime(LocalDateTime.now());
        return addressService.save(receiveAddress);

    }


    /**
     * 删除(修改status=0)
     * @param addressId 根据主键删除(根据主键修改)
     * @return
     */
    @DeleteMapping("/{addrId}")
    public ServerResult remove(@PathVariable("addrId") Integer addressId){

        return addressService.removeById(addressId);

    }


    /**
     * 修改我的某一个收件地址信息
     * @param receiveAddress 页面中接受到的最新的收件地址信息
     * @return 返回是否修改成功
     */
    @PutMapping
    public ServerResult update(ReceiveAddress receiveAddress){
        return addressService.updateById(receiveAddress);
    }



}



ReceiveAddress.java


package com.example.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>
 * 
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */
@TableName("receive_address")
public class ReceiveAddress implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "addr_id", type = IdType.AUTO)
    private Integer addrId;

    private Long receiveUserTelno;

    private String receiveUsername;

    private Integer custId;

    /**
     * 地址的省份
     */
    private String addrProvince;

    /**
     * 地址的城市
     */
    private String addrCity;

    /**
     * 地址的区域
     */
    private String addrArea;

    /**
     * 地址的街道
     */
    private String addrStreet;

    /**
     * 详细地址
     */
    private String addrDetail;

    /**
     * 状态
     */
    private Integer status;

    /**
     * 版本号,用于做乐观锁
     */
    private Integer version;

    /**
     * 数据添加的时间
     */
    private LocalDateTime createTime;

    /**
     * 数据修改时间
     */
    private LocalDateTime updateTime;

    public Integer getAddrId() {
        return addrId;
    }

    public void setAddrId(Integer addrId) {
        this.addrId = addrId;
    }
    public Long getReceiveUserTelno() {
        return receiveUserTelno;
    }

    public void setReceiveUserTelno(Long receiveUserTelno) {
        this.receiveUserTelno = receiveUserTelno;
    }
    public String getReceiveUsername() {
        return receiveUsername;
    }

    public void setReceiveUsername(String receiveUsername) {
        this.receiveUsername = receiveUsername;
    }
    public Integer getCustId() {
        return custId;
    }

    public void setCustId(Integer custId) {
        this.custId = custId;
    }
    public String getAddrProvince() {
        return addrProvince;
    }

    public void setAddrProvince(String addrProvince) {
        this.addrProvince = addrProvince;
    }
    public String getAddrCity() {
        return addrCity;
    }

    public void setAddrCity(String addrCity) {
        this.addrCity = addrCity;
    }
    public String getAddrArea() {
        return addrArea;
    }

    public void setAddrArea(String addrArea) {
        this.addrArea = addrArea;
    }
    public String getAddrStreet() {
        return addrStreet;
    }

    public void setAddrStreet(String addrStreet) {
        this.addrStreet = addrStreet;
    }
    public String getAddrDetail() {
        return addrDetail;
    }

    public void setAddrDetail(String addrDetail) {
        this.addrDetail = addrDetail;
    }
    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }
    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }
    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }
    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "ReceiveAddress{" +
            "addrId=" + addrId +
            ", receiveUserTelno=" + receiveUserTelno +
            ", receiveUsername=" + receiveUsername +
            ", custId=" + custId +
            ", addrProvince=" + addrProvince +
            ", addrCity=" + addrCity +
            ", addrArea=" + addrArea +
            ", addrStreet=" + addrStreet +
            ", addrDetail=" + addrDetail +
            ", status=" + status +
            ", version=" + version +
            ", createTime=" + createTime +
            ", updateTime=" + updateTime +
        "}";
    }
}



ReceiveAddressMapper.java


package com.example.mapper;

import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */
public interface ReceiveAddressMapper extends BaseMapper<ReceiveAddress> {


}



IReceiveAddressService.java


package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.util.ServerResult;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */
public interface IReceiveAddressService  {


    public ServerResult getById(Integer addressId);


    //查询所有的收件地址(当前用户有效的地址数据)
    public ServerResult getAll(Integer customerId);


    public ServerResult save(ReceiveAddress receiveAddress);


    public ServerResult removeById(Integer addressId);


    public ServerResult updateById(ReceiveAddress address);


}



ReceiveAddressServiceImpl.java


package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.ReceiveAddress;
import com.example.mapper.ReceiveAddressMapper;
import com.example.service.IReceiveAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */
@Service
public class ReceiveAddressServiceImpl  implements IReceiveAddressService {



    @Autowired
    private  ReceiveAddressMapper addressMapper;


    @Override
    public ServerResult getById(Integer addressId) {
        ReceiveAddress address = addressMapper.selectById(addressId);
        if(address != null){
            return ServerResult.getSuccess(address);
        }
        return ServerResult.getFail(null);
    }

    //当前登录用户的有效地址
    @Override
    public ServerResult getAll(Integer customerId){
        //select * from
        QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_id",customerId).eq("status",1);
        List<ReceiveAddress> addressList = addressMapper.selectList(wrapper);//select * from table_name where cust_id= and
        if(addressList == null || addressList.size()==0)
            return ServerResult.getFail("暂无收件地址");
        return ServerResult.getSuccess(addressList);



    }



    //添加
    public ServerResult save(ReceiveAddress receiveAddress){//receiveAddress: 没有addr_id
        System.out.println("尚未添加,从页面拿到的收件地址是:" + receiveAddress);
        int rows = addressMapper.insert(receiveAddress);
        if(rows > 0){
            System.out.println("添加成功后:" + receiveAddress);
            return ServerResult.updateSuccess(receiveAddress);//若添加成功,会把数据库中自增的主键addr_id赋值到对象上
        }
        return ServerResult.updateFail(receiveAddress);

    }



    //删除收件地址(实际修改status为0)
    @Override
    public ServerResult removeById(Integer addressId) {
        ReceiveAddress address = addressMapper.selectById(addressId);
        address.setStatus(0);
        address.setVersion(address.getVersion() + 1);

        int rows = addressMapper.updateById(address);//删除成功row =1,删除失败row=0
        if(rows > 0)
            return ServerResult.updateSuccess(address);
        return ServerResult.updateFail(address);
    }


    @Override
    public ServerResult updateById(ReceiveAddress address) {
        int oldVersion = addressMapper.selectById(address.getAddrId()).getVersion();//旧的version值来自db
        address.setUpdateTime(LocalDateTime.now());
        address.setVersion(oldVersion+1);

        int rows = addressMapper.updateById(address);
        if(rows > 0){
            return ServerResult.updateSuccess(address);
        }
        return ServerResult.updateFail(address);


    }
}



ServerResult.java


package com.example.util;

public class ServerResult {
    private int code;
    private String msg;

    private Object data;



    public static ServerResult getSuccess(Object data){
        return new ServerResult(200,"查询成功",data);
    }

    public static ServerResult getFail(Object data){
        return new ServerResult(201,"查询失败",data);
    }


    /**
     * 添加、删除、修改的成功
     * @param data
     * @return
     */

    public static ServerResult updateSuccess(Object data){
        return new ServerResult(200,"处理成功",data);
    }


    /**
     * 添加、删除、修改的失败
     * @param data
     * @return
     */
    public static ServerResult updateFail(Object data){
        return new ServerResult(201,"处理失败",data);
    }


    public static ServerResult loginSuccess(Object data){
        return new ServerResult(200,"登录成功",data);
    }

    public static ServerResult loginFail(Object data){
        return new ServerResult(201,"登失败",data);
    }






    public ServerResult() {
    }


    public ServerResult(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }


    @Override
    public String toString() {
        return "ServerResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}



SpringbootDemoApplication.java



package com.example;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringbootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootDemoApplication.class, args);
	}

}


receive_address.sql




SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for receive_address
-- ----------------------------
DROP TABLE IF EXISTS `receive_address`;
CREATE TABLE `receive_address`  (
  `addr_id` int(0) NOT NULL AUTO_INCREMENT,
  `receive_user_telno` bigint(0) NULL DEFAULT NULL,
  `receive_username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `cust_id` int(0) NULL DEFAULT NULL,
  `addr_province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的省份',
  `addr_city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的城市',
  `addr_area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的区域',
  `addr_street` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的街道',
  `addr_detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '详细地址',
  `status` int(0) NULL DEFAULT NULL COMMENT '状态',
  `version` int(0) NULL DEFAULT NULL COMMENT '版本号,用于做乐观锁',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '数据添加的时间',
  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '数据修改时间',
  PRIMARY KEY (`addr_id`) USING BTREE,
  INDEX `fk_address_customer`(`cust_id`) USING BTREE,
  CONSTRAINT `fk_address_customer` FOREIGN KEY (`cust_id`) REFERENCES `customer` (`cust_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of receive_address
-- ----------------------------
INSERT INTO `receive_address` VALUES (1, NULL, NULL, 1, '江苏省', '苏州市', '园区', '若水路', '若水路99号A501', 1, 1, '2023-08-11 13:47:02', NULL);
INSERT INTO `receive_address` VALUES (2, NULL, NULL, 1, '黑龙江', '大庆市', '市区', '育才路', '育才路88号101', 1, 1, '2023-07-31 13:47:52', NULL);

SET FOREIGN_KEY_CHECKS = 1;





ReceiveAddressMapper.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.example.mapper.ReceiveAddressMapper">

</mapper>


application.yaml




server:
  servlet:
    context-path: /app
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dicts?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456




pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>springboot_demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>springboot_demo</name>
	<description>springboot_demo</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>


		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.28</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.5.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.5.1</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.31</version>
		</dependency>








	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>





04-18 18:18