新增收获地址的开发
- 1.创建地址表
- 2.创建实体类
- 3.持久层的开发
- 3.1规划需要执行的SQL语句
- 3.2Mapper接口与抽象方法
- 3.3配置SQL映射
- 3.4测试
- 4.业务层的开发
- 4.1规划异常
- 4.2接口和抽象方法
- 4.3实现抽象方法
- 4.4测试
- 5.控制层的开发
- 5.1规划异常
- 5.2设计请求
- 5.3处理请求
- 5.4测试
- 6前端页面
1.创建地址表
CREATE TABLE t_address (
aid INT AUTO_INCREMENT COMMENT '收货地址id',
uid INT COMMENT '归属的用户id',
name VARCHAR(20) COMMENT '收货人姓名',
province_name VARCHAR(15) COMMENT '省-名称',
province_code CHAR(6) COMMENT '省-行政代号',
city_name VARCHAR(15) COMMENT '市-名称',
city_code CHAR(6) COMMENT '市-行政代号',
area_name VARCHAR(15) COMMENT '区-名称',
area_code CHAR(6) COMMENT '区-行政代号',
zip CHAR(6) COMMENT '邮政编码',
address VARCHAR(50) COMMENT '详细地址',
phone VARCHAR(20) COMMENT '手机',
tel VARCHAR(20) COMMENT '固话',
tag VARCHAR(6) COMMENT '标签',
is_default INT COMMENT '是否默认:0-不默认,1-默认',
created_user VARCHAR(20) COMMENT '创建人',
created_time DATETIME COMMENT '创建时间',
modified_user VARCHAR(20) COMMENT '修改人',
modified_time DATETIME COMMENT '修改时间',
PRIMARY KEY (aid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.创建实体类
创建com.cy.store.entity.Address新增收获地址的实体类,继承自BaseEntity类,在类中声明与数据表中对应的属性,添加Getters and Setters方法,基于唯一标识aid生成hashCode()和equals()方法。
public class Address extends BaseEntity{
private Integer aid;
private Integer uid;
private String name;
private String provinceName;
private String provinceCode;
private String cityName;
private String cityCode;
private String areaName;
private String areaCode;
private String zip;
private String address;
private String phone;
private String tel;
private String tag;
private Integer isDefault;
// Generate: Getter and Setter、Generate hashCode() and equals()、toString()
}
3.持久层的开发
3.1规划需要执行的SQL语句
新增收获地址,本质上就是执行插入,SQL语句如下:
insert into t_address (字段) values (属性)
select count(*) from t_address where uid=?
3.2Mapper接口与抽象方法
创建com.sdjzu.store.mapper.AddressMapper接口,并在接口中创建抽象方法。
package com.sdjzu.store.mapper;
import com.sdjzu.store.entity.Address;
public interface AddressMapper {
/*新增收获地址*/
/**
* 插入用户收货地址
* @param address 收货地址数据
* @return 返回受影响的行数
*/
Integer insert(Address address);
/*根据id查询记录数*/
/**
* 获取用户收货地址的数量
* @param uid 用户的id
* @return 用户收货地址的数量
*/
Integer countById(Integer uid);
}
3.3配置SQL映射
在AddressMapper.xml中编写两个抽象方法的映射
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--命名就是接口的全类名-->
<mapper namespace="com.sdjzu.store.mapper.AddressMapper">
<resultMap id="AddressEntityMap" type="com.sdjzu.store.entity.Address">
<id column="aid" property="aid"/>
<result column="province_code" property="provinceCode"/>
<result column="province_name" property="provinceName"/>
<result column="city_code" property="cityCode"/>
<result column="city_name" property="cityName"/>
<result column="area_code" property="areaCode"/>
<result column="area_name" property="areaName"/>
<result column="is_default" property="isDefault"/>
<result column="created_user" property="createdUser"/>
<result column="created_time" property="createdTime"/>
<result column="modified_user" property="modifiedUser"/>
<result column="modified_time" property="modifiedTime"/>
</resultMap>
<!--Integer insert(Address address);-->
<insert id="insert" useGeneratedKeys="true" keyProperty="aid">
insert into t_address (
uid, name, province_name, province_code, city_name, city_code, area_name, area_code, zip,
address, phone, tel,tag, is_default, created_user, created_time, modified_user, modified_time
)values(
#{uid}, #{name}, #{provinceName}, #{provinceCode}, #{cityName}, #{cityCode}, #{areaName},
#{areaCode}, #{zip}, #{address}, #{phone}, #{tel}, #{tag}, #{isDefault}, #{createdUser},
#{createdTime}, #{modifiedUser}, #{modifiedTime}
)
</insert>
<!--Integer countById(Integer uid);-->
<select id="countById" resultType="java.lang.Integer">
select count(*) from t_address where uid=#{uid}
</select>
</mapper>
3.4测试
@Test
public void insert(){
Address address = new Address();
address.setUid(38);
address.setName("dyj");
address.setAddress("龙湖");
address.setPhone("123345");
addressMapper.insert(address);
}
@Test
public void count(){
Integer integer = addressMapper.countById(38);
System.out.println(integer);
}
4.业务层的开发
4.1规划异常
收获地址不可以超过20,超过了就会跑业务层的异常
package com.sdjzu.store.service.ex;
public class AddressCountLimitException extends ServiceException{
public AddressCountLimitException() {
super();
}
public AddressCountLimitException(String message) {
super(message);
}
public AddressCountLimitException(String message, Throwable cause) {
super(message, cause);
}
public AddressCountLimitException(Throwable cause) {
super(cause);
}
protected AddressCountLimitException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
4.2接口和抽象方法
package com.sdjzu.store.service;
import com.sdjzu.store.entity.Address;
/*收获地址管理*/
public interface IAddressService {
/**
* 新增收获地址
* @param uid 根据uid获取收获地址
* @param username 更新表中的数据
* @param address 表单提交的数据你
*/
void addAddress(Integer uid, String username, Address address);
}
4.3实现抽象方法
package com.sdjzu.store.service.impl;
import com.sdjzu.store.entity.Address;
import com.sdjzu.store.mapper.AddressMapper;
import com.sdjzu.store.service.IAddressService;
import com.sdjzu.store.service.ex.AddressCountLimitException;
import com.sdjzu.store.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class AddressServiceImpl implements IAddressService {
@Autowired
private AddressMapper addressMapper;
@Value("${user.address.maxCount}")
private int maxCount;
@Override
public void addAddress(Integer uid, String username, Address address) {
/*判断收获地址的数量*/
Integer row = addressMapper.countById(uid);
if(row>maxCount){
throw new AddressCountLimitException("数量超过20");
}
/*封装数据*/
address.setUid(uid);
address.setCreatedUser(username);
address.setModifiedUser(username);
address.setCreatedTime(new Date());
address.setModifiedTime(new Date());
/*判断是否为默认地址*/
Integer isDefault = row == 0 ? 1:0;
address.setIsDefault(isDefault);
/*调用插入的方法,并判断受影响的行数,判断是否插入成功*/
Integer insert = addressMapper.insert(address);
if(insert==0){
throw new InsertException("插入失败");
}
}
}
4.4测试
package com.sdjzu.store.service;
import com.sdjzu.store.entity.Address;
import com.sdjzu.store.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AddressServiceTest {
@Autowired
private IAddressService addressService;
@Test
public void insert(){
Address address = new Address();
address.setName("dyj");
address.setAddress("龙湖");
address.setPhone("123345");
addressService.addAddress(38,"ljl",address);
}
}
5.控制层的开发
5.1规划异常
else if (e instanceof AddressCountLimitException) {
result.setState(4000);
}
5.2设计请求
请求路径:/address/addAddress
请求参数:Address address,HttpSession session
请求类型: POST
响应结果: JsonResult
5.3处理请求
@RequestMapping("addAddress")
public JsonResult<Void> addAddress(HttpSession session, Address address){
Integer uid = getUidFromSession(session);
String username = getUsernameFromSession(session);
addressService.addAddress(uid,username,address);
return new JsonResult<>(ok);
}
5.4测试
先启动项目,再访问http://localhost:8080/store/address/addAddress
6前端页面
1.在addAddress.html页面中配置新增收货地址表单的属性。给form表单添加id="form-add-new-address"属性、"请输入收货人姓名"添加name="name"属性、"请输入邮政编码"添加name="zip"属性、"输入详细的收货地址,小区名称、门牌号等"添加name="address"属性、"请输入手机号码"添加name="phone"属性、"请输入固定电话号码"添加name="tel"属性、"请输入地址类型,如:家、公司或者学校"添加name="tag"属性、"保存"按钮添加id="btn-add-new-address"属性。以上属性如果已经添加无需重复添加。
2.在addAddress.html页面中body标签内部的最后,添加script标签用于编写JavaScript程序。
<script type="text/javascript">
$("#btn-add-new-address").click(function () {
$.ajax({
url: "/address/addAddress",
type: "POST",
data: $("#form-add-new-address").serialize(),
success: function (json) {
if(json.sate==200){
alert("新增成功");
}else {
alert("新增失败");
}
},
error: function (xhr) {
alert("登录过期");
location.href="login.html";
}
})
})
</script>