1. mapper接口
public interface DistrictMapper {
/**
* 根据code查询区域名称
* @param code
* @return
*/
String findNameByCode(String code);
}
2. sql映射文件
<select id="findNameByCode" resultType="java.lang.String">
select name from t_dict_district where code=#{code}
</select>
3. 测试
@Test
public void findNameByCode() {
String name = districtMapper.findNameByCode("610000");
System.out.println(name);
}
结果应输出:陕西省
4. 完善AddressServiceImpl类➡addNewAddress()方法
findNameByCode()方法辅助addNewAddress()方法,在新增收货地址时设置省市区名称:
package com.cy.store.service.impl;
import com.cy.store.entity.Address;
import com.cy.store.ex.AddressServiceEx.AddressCountLimitException;
import com.cy.store.ex.UserServiceEx.InsertException;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.mapper.DistrictMapper;
import com.cy.store.service.IAddressService;
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 {
@Value("${user.address.max-count}")
private Integer maxCount;
@Autowired
private AddressMapper addressMapper;
//新增代码
@Autowired
private DistrictMapper districtMapper;
@Override
public void addNewAddress(Integer uid, String username, Address address) {
Integer count = addressMapper.countByUid(uid);
if(count >= maxCount) {
throw new AddressCountLimitException("收货地址数量超出限制");
}
//新增代码:设置省市区名称
String provinceName = districtMapper.findNameByCode(address.getProvinceCode());
String cityName = districtMapper.findNameByCode(address.getCityCode());
String areaName = districtMapper.findNameByCode(address.getAreaCode());
address.setProvinceName(provinceName);
address.setCityName(cityName);
address.setAreaName(areaName);
address.setUid(uid);
Integer isDefault = count == 0 ? 1 : 0;
address.setIsDefault(isDefault);
address.setCreateBy(username);
address.setCreateTime(new Date());
address.setModifyBy(username);
address.setModifyTime(new Date());
Integer rows = addressMapper.insert(address);
if(rows != 1) {
throw new InsertException("新增收货地址时出现了未知异常");
}
}
}