首先,确保你有两个数据模型:
Repertory
和Address而且mysql数据库有两个表,
address表和repertory表(address表的id和repertory表的address_id关联)public class Repertory { private Integer id; private String name; private Integer amount; private Integer addressId; // 外键,关联Address表的id // getters and setters } public class Address { private Integer id; private String location; // 地址信息 // getters and setters }
接下来,定义MyBatis的Mapper XML,用于操作库存数据。
<mapper namespace="com.example.mapper.RepertoryMapper"> <!-- 根据商品名称和地址ID查询库存 --> <select id="selectRepertoryByProductNameAndAddressId" resultType="Repertory"> SELECT id, name, amount, address_id FROM repertory WHERE name = #{productName} AND address_id = #{addressId} </select> <!-- 更新库存数量 --> <update id="updateRepertoryAmount"> UPDATE repertory SET amount = amount - #{amountToTransfer} WHERE id = #{repertoryId} </update> <!-- 为指定地址增加库存数量 --> <update id="increaseRepertoryAmountByAddressId"> UPDATE repertory SET amount = amount + #{amountToTransfer} WHERE name = #{productName} AND address_id = #{newAddressId} </update> </mapper>
定义一个Mapper接口,用于MyBatis的映射。
public interface RepertoryMapper { Repertory selectRepertoryByProductNameAndAddressId(@Param("productName") String productName, @Param("addressId") Integer addressId); void updateRepertoryAmount(@Param("repertoryId") Integer repertoryId, @Param("amountToTransfer") Integer amountToTransfer); void increaseRepertoryAmountByAddressId(@Param("productName") String productName, @Param("newAddressId") Integer newAddressId, @Param("amountToTransfer") Integer amountToTransfer); }
接下来是service和serviceImpl层
public interface RepertoryService { void transferStock(String productName, Integer fromAddressId, Integer toAddressId, Integer amountToTransfer); }
@Service public class RepertoryServiceImpl implements RepertoryService { @Autowired private RepertoryMapper repertoryMapper; @Override public void transferStock(String productName, Integer fromAddressId, Integer toAddressId, Integer amountToTransfer) { Repertory repertory = repertoryMapper.selectRepertoryByProductNameAndAddressId(productName, fromAddressId); if (repertory != null && repertory.getAmount() >= amountToTransfer) { repertoryMapper.updateRepertoryAmount(repertory.getId(), amountToTransfer); repertoryMapper.increaseRepertoryAmountByAddressId(productName, toAddressId, amountToTransfer); } else { throw new IllegalArgumentException("Not enough stock or invalid parameters."); } } }
最后,创建一个RESTful风格的Controller来处理库存转移的请求。
@RestController @RequestMapping("/api/inventory") public class InventoryController { @Autowired private RepertoryService repertoryService; @PostMapping("/transfer") public void transferStock(@RequestParam String productName, @RequestParam Integer fromAddressId, @RequestParam Integer toAddressId, @RequestParam Integer amountToTransfer) { repertoryService.transferStock(productName, fromAddressId, toAddressId, amountToTransfer); } }
最后可以自己添加JsonResult来响应结果,用swagger测试成功从一个地方的库存转移到另一个地方。