1)先写两个 DTO(新增、修改)
ShopSaveDTO.java(新增用)
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ShopSaveDTO {
private String name;
private String address;
private Long typeId;
private String phone;
private BigDecimal avgPrice;
}
ShopUpdateDTO.java(修改用)
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ShopUpdateDTO {
private Long id; // 修改必须传id
private String name;
private String address;
private Long typeId;
private String phone;
private BigDecimal avgPrice;
}
2)Controller(完整,接收 DTO)
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/shop")
public class ShopController {
@Resource
private ShopService shopService;
// 查询
@GetMapping("/{id}")
public Result queryById(@PathVariable Long id) {
return shopService.queryById(id);
}
// 新增(接收 ShopSaveDTO)
@PostMapping
public Result saveShop(@RequestBody ShopSaveDTO dto) {
return shopService.saveShop(dto);
}
// 修改(接收 ShopUpdateDTO)
@PutMapping
public Result updateShop(@RequestBody ShopUpdateDTO dto) {
return shopService.updateShop(dto);
}
// 删除
@DeleteMapping("/{id}")
public Result deleteShop(@PathVariable Long id) {
return shopService.deleteShop(id);
}
}
3)Service 接口
import com.baomidou.mybatisplus.extension.service.IService;
public interface ShopService extends IService<Shop> {
Result queryById(Long id);
Result saveShop(ShopSaveDTO dto);
Result updateShop(ShopUpdateDTO dto);
Result deleteShop(Long id);
}
4)ServiceImpl(完整 + BeanUtils.copyProperties)
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.redis.core.StringRedisTemplate;
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private CacheClient cacheClient;
private static final String CACHE_SHOP_KEY = "cache:shop:";
// ====================== 查询(你原来的逻辑)======================
@Override
public Result queryById(Long id) {
Shop shop = cacheClient.queryWithPassThrough(
CACHE_SHOP_KEY,
id,
Shop.class,
this::getById,
30L,
java.util.concurrent.TimeUnit.MINUTES
);
if (shop == null) {
return Result.fail("店铺不存在");
}
return Result.ok(shop);
}
// ====================== 新增 ======================
@Override
@Transactional
public Result saveShop(ShopSaveDTO dto) {
Shop shop = new Shop();
BeanUtils.copyProperties(dto, shop); // DTO → 实体
save(shop);
return Result.ok();
}
// ====================== 修改 ======================
@Override
@Transactional
public Result updateShop(ShopUpdateDTO dto) {
Shop shop = new Shop();
BeanUtils.copyProperties(dto, shop); // DTO → 实体
updateById(shop);
// 删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY + dto.getId());
return Result.ok();
}
// ====================== 删除 ======================
@Override
@Transactional
public Result deleteShop(Long id) {
removeById(id);
stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
return Result.ok();
}
}