有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

大家好,我想在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);
    }
}

这些是模型。 谢谢你的邀请 ........................ ......................... ............................... .................................... ........................................................ ..............................................................


共 (1) 个答案

  1. # 1 楼答案

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

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

    然后,您可以使用JpaRepository#findAll获得所有预订,但这并不等于您的地图。我仍然不确定,当你有这种关系时,为什么你需要一张地图,但以下方法可以(前提是你的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