Spring Boot REST API设计-如何处理重复数据?

5hcedyr0  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(149)

我是REST API开发的新手。我正在构建一个API来获取农民的所有收获。农民表有一个主键farmer_id。收获表有一个主键harvest_id和一个指向农民表的外键。我正在使用这个查询来获取收获数据。

  1. public List<Harvest> getFarmerHarvests(Long farmerId) {
  2. String jpql = "SELECT h FROM Harvest h WHERE h.farmer.farmerId = :farmerId";
  3. TypedQuery<Harvest> query = entityManager.createQuery(jpql, Harvest.class);
  4. query.setParameter("farmerId", farmerId);
  5. return query.getResultList();
  6. }

字符串
这就是结果集的样子

  1. [
  2. {
  3. "harvestId": 1,
  4. "cropName": "Barley",
  5. "farmer": {
  6. "username": "don_joe",
  7. "firstname": "Don",
  8. "lastname": "Joe",
  9. "password": "$2a$10$l0ExQAoGIdk.ULksc/W66eXEqWelt3Jo9Il7aPgJM7LE0G9Ok2Dnm",
  10. "email": "[email protected]",
  11. "address": "123 Main Street",
  12. "city": "Seattle",
  13. "phno": "+1 1234567890",
  14. "enabled": true,
  15. "farmerId": 1
  16. },
  17. "harvestDate": "2023-12-23T18:30:00.000+00:00",
  18. "expiryDate": "2023-12-31T18:30:00.000+00:00",
  19. "quantity": 10,
  20. "units": "Kg (Kilograms)",
  21. "pricePerQuantity": 100,
  22. "smallestUnitSize": 1,
  23. "imageUrl": "no url"
  24. },
  25. {
  26. "harvestId": 2,
  27. "cropName": "Wheat",
  28. "farmer": {
  29. "username": "don_joe",
  30. "firstname": "Don",
  31. "lastname": "Joe",
  32. "password": "$2a$10$l0ExQAoGIdk.ULksc/W66eXEqWelt3Jo9Il7aPgJM7LE0G9Ok2Dnm",
  33. "email": "[email protected]",
  34. "address": "123 Main Street",
  35. "city": "Seattle",
  36. "phno": "+1 1234567890",
  37. "enabled": true,
  38. "farmerId": 1
  39. },
  40. "harvestDate": "2023-12-23T18:30:00.000+00:00",
  41. "expiryDate": "2024-02-29T18:30:00.000+00:00",
  42. "quantity": 30,
  43. "units": "Kg (Kilograms)",
  44. "pricePerQuantity": 300,
  45. "smallestUnitSize": 1,
  46. "imageUrl": "no url"
  47. }
  48. ]


正如您所看到的,农民信息在两个对象中重复。最佳实践是什么?数据在API响应中应该是这样的吗?或者我应该排除此数据?如果是,我如何排除它?
对于我的用例,我不需要每个对象上的Farmer数据。

wfauudbj

wfauudbj1#

反转JSON响应的设计,以模拟一对多关系,而不是多对一关系。
举例来说:

  1. {
  2. Farmer: Bob,
  3. Harvests: [
  4. { Harvest: 1 },
  5. { Harvest: 2 }
  6. ...etc
  7. ]
  8. }

字符串
考虑下面的SQL查询,它具有一对多的Author to Posts关系,其中当查询作者时,属于他们的所有帖子都在嵌套数组中返回。

  1. SELECT
  2. Authors.author_id,
  3. Authors.author_name,
  4. array_agg(Posts.post_content) AS posts
  5. FROM
  6. Authors
  7. JOIN
  8. Posts ON Authors.author_id = Posts.author_id
  9. WHERE
  10. Authors.author_id = 'specific_author_id'
  11. GROUP BY
  12. Authors.author_id;


基本上是农民多岗的结构。

展开查看全部

相关问题