如何在 Jpa 存储库中创建地图

How to create a Map in a Jpa Repository

大家好,我想在 JPA 存储库中创建一个 HashMap/Map,但我不知道怎么做。

@Repository
public interface CurrentDeployedReservations extends JpaRepository<Reservation, CustomTable>{
    //Map(CustomTable, Reservation) findMap()?
}

谢谢


@SuppressWarnings("serial")
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Reservation implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private Boolean accepted;
    private Long t_ID;
    @OneToOne
    @JoinColumn(name = "user_id")
    @JsonManagedReference
    private User user;
    @OneToOne
    @JoinColumn(name = "table_id")
    @JsonBackReference
    private CustomTable table;
    private String time;
    private int numberOfPeople;
}

@SuppressWarnings("serial")
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomTable implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private Boolean busy;
    private Boolean full;
    @JsonIgnore
    @OneToMany(mappedBy = "table", orphanRemoval = true, fetch = FetchType.EAGER)
    @JsonManagedReference
    private List<Reservation> reservations;
    
    public void addReservation(Reservation r) {
        this.reservations.add(r);
        r.setTable(this);
    }
    public void removeReservation(Reservation r) {
        r.setTable(null);
        this.reservations.remove(r);
    }
}

这是模型。 谢谢你的慰问 ........................................ .................................. ................................... ..................................... ..................................................... …… ..................................................... ......

我想你误会了JpaRepository,用法是:JpaRepository<T,ID>。 在您的情况下,这意味着:

@Repository
public interface CurrentDeployedReservations extends JpaRepository<Reservation, Long> {

}

然后您可以使用 JpaRepository#findAll 获取所有 Reservations,但这不等于您的 Map。我仍然不确定为什么当你有这种关系时你需要一个地图,但以下是可行的(前提是你的 CustomTable 有一个 getter 用于预订):

@Repository
public interface CustomTableRepository extends JpaRepository<CustomTable, Long> {
  public Map<CustomTable, List<Reservation>> getAll() {
    return findAll().stream()
             .collect(Collectors.toMap(c -> c, CustomTable::getReservations));
  }
}

您在预订 customeTable 字段中的 @OneToOne 关系应为 @ManyToOne