【问题标题】:Sorting by a field that is not in the database按不在数据库中的字段排序
【发布时间】:2023-01-03 00:00:42
【问题描述】:

我面临以下问题。 我有 2 个实体(简单代码):

class Vehicle(id: UUID, name: String, updatedBy: User)

class User(id: UUID)

我通过 ID 在 Cognito 服务中获取用户名。现在我想按用户名向 Vehicle 表添加排序。我在我的项目中使用 Spring Data。而且我不知道如何将用户名字段添加到存储库进行排序。

我希望使用 SPEL 来解决我的问题,但我不确定它是否对我有帮助。

【问题讨论】:

  • 排序就像您想使用 JPA 从数据库中查询并获取基于 username 排序的结果,还是您想基于 username 对 Java 对象进行排序?
  • 我想使用 jpa 中的多种排序和分页。

标签: java spring hibernate kotlin spring-data-jpa


【解决方案1】:

假设您有一个用户 ID 及其名称的映射(来自 Cognito),以及一个 Vehicles 列表,您可以像这样排序:

final UUID user1Id = UUID.randomUUID();
final UUID user2Id = UUID.randomUUID();
final UUID user3Id = UUID.randomUUID();

final Map<UUID, String> userNameMap = Map.ofEntries(
    Map.entry(user1Id, "User 1"),
    Map.entry(user2Id, "User 2"),
    Map.entry(user3Id, "User 3")
);

final List<Vehicle> vehicles = List.of(
    new Vehicle(UUID.randomUUID(), "Vehicle 1", new User(user1Id)),
    new Vehicle(UUID.randomUUID(), "Vehicle 2", new User(user2Id)),
    new Vehicle(UUID.randomUUID(), "Vehicle 3", new User(user3Id))
);

final List<Vehicle> sortedVehicles = vehicles.stream()
    .sorted(Comparator.comparing(o -> userNameMap.get(o.getUpdatedBy().getId())))
    .collect(Collectors.toUnmodifiableList());

【讨论】:

  • 有没有办法在存储库层中使用排序?因为我在数据库中有超过 10000 个对象。我也想使用分页
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多